crypto_profile/
sealbox_wire.rs1use crate::error::CryptoError;
3
4pub const VERSION: u8 = 1;
6pub const EPHEMERAL_KEY_LEN: usize = 97;
8pub const NONCE_LEN: usize = 12;
10pub const TAG_LEN: usize = 16;
12pub const HEADER_LEN: usize = 1 + EPHEMERAL_KEY_LEN + NONCE_LEN;
14pub const MIN_BLOB_LEN: usize = HEADER_LEN + 1 + TAG_LEN;
16const UNCOMPRESSED_POINT: u8 = 0x04;
17
18#[derive(Debug)]
20pub struct BlobParts<'a> {
21 pub ephemeral: &'a [u8],
23 pub nonce: [u8; NONCE_LEN],
25 pub sealed: &'a [u8],
27}
28
29pub fn sealed_len(plaintext_len: usize) -> usize {
31 HEADER_LEN + plaintext_len + TAG_LEN
32}
33
34pub fn parse_blob(blob: &[u8]) -> Result<BlobParts<'_>, CryptoError> {
36 if blob.len() < MIN_BLOB_LEN {
37 return Err(CryptoError::SealBlob);
38 }
39 if blob[0] != VERSION {
40 return Err(CryptoError::SealVersion);
41 }
42 if blob[1] != UNCOMPRESSED_POINT {
43 return Err(CryptoError::SealEphemeralKey);
44 }
45 let nonce = blob[1 + EPHEMERAL_KEY_LEN..HEADER_LEN]
46 .try_into()
47 .map_err(|_| CryptoError::SealBlob)?;
48 Ok(BlobParts {
49 ephemeral: &blob[1..1 + EPHEMERAL_KEY_LEN],
50 nonce,
51 sealed: &blob[HEADER_LEN..],
52 })
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 fn blob(len: usize) -> Vec<u8> {
60 let mut b = vec![0u8; len];
61 b[0] = VERSION;
62 b[1] = 0x04;
63 b
64 }
65
66 #[test]
67 fn the_v1_layout_is_pinned() {
68 assert_eq!(
69 (VERSION, EPHEMERAL_KEY_LEN, NONCE_LEN, TAG_LEN, HEADER_LEN),
70 (1, 97, 12, 16, 110)
71 );
72 assert_eq!(MIN_BLOB_LEN, 127);
73 assert_eq!(sealed_len(95), 110 + 95 + 16);
74 }
75
76 #[test]
77 fn a_blob_splits_into_ephemeral_nonce_and_sealed_bytes() {
78 let mut b = blob(MIN_BLOB_LEN);
79 b[EPHEMERAL_KEY_LEN] = 0xEE;
80 b[1 + EPHEMERAL_KEY_LEN] = 0xAA;
81 b[HEADER_LEN - 1] = 0xAB;
82 b[HEADER_LEN] = 0xBB;
83 let p = parse_blob(&b).unwrap();
84 assert_eq!(
85 (
86 p.ephemeral.len(),
87 p.ephemeral[0],
88 p.ephemeral[EPHEMERAL_KEY_LEN - 1]
89 ),
90 (EPHEMERAL_KEY_LEN, 0x04, 0xEE)
91 );
92 assert_eq!((p.nonce[0], p.nonce[NONCE_LEN - 1]), (0xAA, 0xAB));
93 assert_eq!((p.sealed.len(), p.sealed[0]), (1 + TAG_LEN, 0xBB));
94 assert_eq!(
95 parse_blob(&blob(4096)).unwrap().sealed.len(),
96 4096 - HEADER_LEN
97 );
98 }
99
100 #[test]
101 fn a_short_blob_or_another_version_or_point_form_is_refused_in_that_order() {
102 assert!(matches!(
103 parse_blob(&blob(MIN_BLOB_LEN - 1)),
104 Err(CryptoError::SealBlob)
105 ));
106 assert!(matches!(parse_blob(&[]), Err(CryptoError::SealBlob)));
107 let mut short_v2 = blob(MIN_BLOB_LEN - 1);
108 short_v2[0] = 2;
109 assert!(matches!(parse_blob(&short_v2), Err(CryptoError::SealBlob)));
110 let mut v2 = blob(MIN_BLOB_LEN);
111 v2[0] = 2;
112 v2[1] = 0x02;
113 assert!(matches!(parse_blob(&v2), Err(CryptoError::SealVersion)));
114 let mut compressed = blob(MIN_BLOB_LEN);
115 compressed[1] = 0x02;
116 assert!(matches!(
117 parse_blob(&compressed),
118 Err(CryptoError::SealEphemeralKey)
119 ));
120 }
121}