src/crypto/aead.bend
bend-collections-laws-crypto@1.0.0.0 · 88 lines · 10 definitions
1import Base
2import bend-collections-laws-crypto@1.0.0.0/src/crypto/aead/chacha20poly1305.bend as CP
3import bend-collections-laws-crypto@1.0.0.0/src/crypto/aesgcm.bend as GCM
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37type Alg is Data:
38 CHACHA20_POLY1305{}
39 XCHACHA20_POLY1305{}
40 AES_128_GCM{}
41 AES_256_GCM{}
42
43def key_size(alg: Alg) -> Nat:
44 match alg:
45 case CHACHA20_POLY1305{}: 32n
46 case XCHACHA20_POLY1305{}: 32n
47 case AES_128_GCM{}: 16n
48 case AES_256_GCM{}: 32n
49
50def nonce_size(alg: Alg) -> Nat:
51 match alg:
52 case CHACHA20_POLY1305{}: 12n
53 case XCHACHA20_POLY1305{}: 24n
54 case AES_128_GCM{}: 12n
55 case AES_256_GCM{}: 12n
56
57def tag_size() -> Nat:
58 16n
59
60
61def seal(alg: Alg, +key: List<&2, U32>, +nonce: List<&2, U32>, +aad: List<&2, U32>, +pt: List<&2, U32>) -> Maybe<&2, List<&2, U32>>:
62 match alg:
63 case CHACHA20_POLY1305{}: Some{CP.seal(key, nonce, aad, pt)}
64 case XCHACHA20_POLY1305{}: Some{CP.xseal(key, nonce, aad, pt)}
65 case AES_128_GCM{}: GCM.aes128_gcm_encrypt(key, nonce, aad, pt)
66 case AES_256_GCM{}: GCM.aes256_gcm_encrypt(key, nonce, aad, pt)
67
68
69def open(alg: Alg, +key: List<&2, U32>, +nonce: List<&2, U32>, +aad: List<&2, U32>, +data: List<&2, U32>) -> Maybe<&2, List<&2, U32>>:
70 match alg:
71 case CHACHA20_POLY1305{}: CP.open(key, nonce, aad, data)
72 case XCHACHA20_POLY1305{}: CP.xopen(key, nonce, aad, data)
73 case AES_128_GCM{}: GCM.aes128_gcm_decrypt(key, nonce, aad, data)
74 case AES_256_GCM{}: GCM.aes256_gcm_decrypt(key, nonce, aad, data)
75
76def valid(+alg: Alg, +key: List<&2, U32>, +nonce: List<&2, U32>) -> Bool:
77 Bool.and(Nat.is_eq(List.length(&2, U32, key), key_size(alg)), Nat.is_eq(List.length(&2, U32, nonce), nonce_size(alg)))
78
79def when_open(ok: Bool, r: Maybe<&2, List<&2, U32>>) -> Maybe<&2, List<&2, U32>>:
80 match ok:
81 case True{}: r
82 case False{}: None{}
83
84def encrypt(+alg: Alg, +key: List<&2, U32>, +nonce: List<&2, U32>, +aad: List<&2, U32>, +pt: List<&2, U32>) -> Maybe<&2, List<&2, U32>>:
85 when_open(valid(alg, key, nonce), seal(alg, key, nonce, aad, pt))
86
87def decrypt(+alg: Alg, +key: List<&2, U32>, +nonce: List<&2, U32>, +aad: List<&2, U32>, +data: List<&2, U32>) -> Maybe<&2, List<&2, U32>>:
88 when_open(valid(alg, key, nonce), open(alg, key, nonce, aad, data))