platform_encryption/
contact_info.rs1use aes::Aes256;
5
6use crate::aes::encrypt_aes_256_cbc;
7use crate::error::CryptoError;
8
9pub fn encrypt_enc_to_user_id(key: &[u8; 32], to_user_id: &[u8; 32]) -> [u8; 32] {
19 use aes::cipher::{BlockEncrypt, KeyInit};
20
21 let cipher = Aes256::new(key.into());
22 let mut out = *to_user_id;
23 let (block1, block2) = out.split_at_mut(16);
24 cipher.encrypt_block(block1.into());
25 cipher.encrypt_block(block2.into());
26 out
27}
28
29pub fn decrypt_enc_to_user_id(key: &[u8; 32], ciphertext: &[u8; 32]) -> [u8; 32] {
32 use aes::cipher::{BlockDecrypt, KeyInit};
33
34 let cipher = Aes256::new(key.into());
35 let mut out = *ciphertext;
36 let (block1, block2) = out.split_at_mut(16);
37 cipher.decrypt_block(block1.into());
38 cipher.decrypt_block(block2.into());
39 out
40}
41
42pub fn encrypt_private_data(key: &[u8; 32], iv: &[u8; 16], plaintext: &[u8]) -> Vec<u8> {
48 let mut out = Vec::with_capacity(16 + plaintext.len() + 16);
49 out.extend_from_slice(iv);
50 out.extend_from_slice(&encrypt_aes_256_cbc(key, iv, plaintext));
51 out
52}
53
54pub fn decrypt_private_data(key: &[u8; 32], blob: &[u8]) -> Result<Vec<u8>, CryptoError> {
57 use crate::aes::decrypt_aes_256_cbc;
58
59 if blob.len() < 16 {
60 return Err(CryptoError::InvalidCiphertextLength);
61 }
62 let iv: [u8; 16] = blob[..16].try_into().expect("length checked above");
63 decrypt_aes_256_cbc(key, &iv, &blob[16..])
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn enc_to_user_id_round_trips_and_is_two_independent_blocks() {
72 let key = [0x11u8; 32];
73 let mut id = [0u8; 32];
74 for (i, b) in id.iter_mut().enumerate() {
75 *b = i as u8;
76 }
77
78 let ct = encrypt_enc_to_user_id(&key, &id);
79 assert_ne!(ct, id, "ciphertext must differ from plaintext");
80 assert_eq!(decrypt_enc_to_user_id(&key, &ct), id, "round trip");
81
82 let same_blocks = [0xAAu8; 32];
87 let ct2 = encrypt_enc_to_user_id(&key, &same_blocks);
88 assert_eq!(
89 ct2[..16],
90 ct2[16..],
91 "ECB: identical blocks encrypt identically"
92 );
93
94 assert_ne!(decrypt_enc_to_user_id(&[0x22u8; 32], &ct), id);
96 }
97
98 #[test]
99 fn private_data_round_trips_with_prepended_iv() {
100 let key = [0x33u8; 32];
101 let iv = [0x44u8; 16];
102 let plaintext = b"[\"alias\",\"note\",false] stand-in cbor";
106
107 let blob = encrypt_private_data(&key, &iv, plaintext);
108 assert_eq!(&blob[..16], &iv, "IV must be prepended verbatim");
109 assert!(blob.len() >= 48, "IV + padded CBC reaches the schema floor");
110
111 let plain = decrypt_private_data(&key, &blob).expect("decrypt");
112 assert_eq!(plain, plaintext);
113
114 assert!(matches!(
116 decrypt_private_data(&key, &blob[..10]),
117 Err(CryptoError::InvalidCiphertextLength)
118 ));
119 }
120}