inst_lc.bend

bend-osdev-crypto@0.1.0.0 · 39 lines · 4 definitions

1# The adapter for legacy-ciphers: its error type mapped onto CrError, its
2# key schedules as the block-cipher interface's ~key, and the XOR of its
3# 64-bit block LcBlock64 (an open type). The 64-bit block format is
4# legacy-ciphers' own LcBlock64.of_octets and LcBlock64.to_octets, whose law
5# it proves (block64_octets_round_trip); the 128-bit ciphers use
6# inst_cm.bend's format.
7#
8# Each cipher is then an instance with no code of its own, for example SM4:
9#   ~S.LcSm4Key, ~M.CmBlock, ~16n, ~CrLc.key(~S.LcSm4Key, ~S.LcSm4.key),
10#   ~S.LcSm4.encrypt, ~S.LcSm4.decrypt,
11#   ~CrBlk128.of_octets, ~CrBlk128.to_octets, ~CrBlk128.xor
12# (README.md lists every instance).
13import Base
14import bend-osdev-bytes@0.1.0.0/bytes.bend as B
15import bend-osdev-legacy-ciphers@0.1.0.0/legacy_ciphers.bend as L
16import bend-osdev-crypto@0.1.0.0/crypto.bend as Cr
17
18def CrLc.err(e: L.LcError) -> Cr.CrError:
19  match e:
20    case L.LcBadKeyLength{n}:
21      Cr.CrBadKeyLength{n}
22    case L.LcBadIvLength{n}:
23      Cr.CrBadIvLength{n}
24    case L.LcNotBlockMultiple{n}:
25      Cr.CrNotBlockMultiple{n}
26
27# a legacy-ciphers result as an interface result
28def CrLc.lift(~A: Data, r: Result<&2, &2, L.LcError, A>) -> Result<&2, &2, Cr.CrError, A>:
29  Cr.CrError.lift(~L.LcError, ~A, ~CrLc.err, r)
30
31# a legacy-ciphers key schedule as the interface's ~key
32def CrLc.key(~K: Data, ~key: B.Octets -> Result<&2, &2, L.LcError, K>, o: B.Octets) -> Result<&2, &2, Cr.CrError, K>:
33  CrLc.lift(~K, key(o))
34
35# The 64-bit block's XOR
36def CrBlk64.xor(a: L.LcBlock64, b: L.LcBlock64) -> L.LcBlock64:
37  match a b:
38    case L.LcBlock64{a0, a1} L.LcBlock64{b0, b1}:
39      L.LcBlock64{U32.xor(a0, b0), U32.xor(a1, b1)}