Skip to main content

platform_encryption/
contact_info.rs

1//! DIP-15 `contactInfo` field encryption: `encToUserId` (AES-256-ECB) and
2//! `privateData` (`IV ‖ AES-256-CBC`).
3
4use aes::Aes256;
5
6use crate::aes::encrypt_aes_256_cbc;
7use crate::error::CryptoError;
8
9/// Encrypt a 32-byte identity id with AES-256-ECB (DIP-15
10/// `contactInfo.encToUserId`).
11///
12/// Exactly two raw AES blocks — **no IV, no padding**. ECB is sound
13/// for this one field per DIP-15's own analysis: the plaintext is
14/// itself a SHA-256 output (pseudorandom, no repeated-block structure)
15/// and the key — a dedicated hardened child at
16/// `rootEncryptionKey/2^16'/index'` — is never reused for any other
17/// purpose. Do NOT use this for anything but `encToUserId`.
18pub 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
29/// Decrypt a 32-byte `contactInfo.encToUserId` ciphertext
30/// (inverse of [`encrypt_enc_to_user_id`]).
31pub 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
42/// Encrypt a `contactInfo.privateData` plaintext (the DIP-15 var-int
43/// encoding, built by the wallet's `encode_private_data`) as
44/// `IV(16) ‖ AES-256-CBC(plaintext)` — the same prepended-IV layout
45/// `encryptedPublicKey` uses (DIP-15 doesn't pin the layout for this
46/// field; we adopt the same convention).
47pub 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
54/// Decrypt a `contactInfo.privateData` blob (inverse of
55/// [`encrypt_private_data`]).
56pub 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        // ECB property we rely on: equal plaintext blocks → equal
83        // ciphertext blocks (sound here only because identity ids are
84        // hash outputs). This pins that the implementation really is
85        // ECB and not CBC-with-zero-IV.
86        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        // Wrong key must not round-trip.
95        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        // Minimal CBOR-ish payload; the schema floor is 48 bytes of
103        // ciphertext which IV(16) + one padded block satisfies — the
104        // length policy lives at the document-build layer, not here.
105        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        // Truncated blob → typed error, not a panic.
115        assert!(matches!(
116            decrypt_private_data(&key, &blob[..10]),
117            Err(CryptoError::InvalidCiphertextLength)
118        ));
119    }
120}