ipcrypt_rs/
deterministic.rs

1use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit};
2use aes::Aes128;
3use aes::Block;
4use std::net::IpAddr;
5
6use crate::common::{bytes_to_ip, ip_to_bytes};
7
8/// A structure representing the IPCrypt context for deterministic mode.
9pub struct Ipcrypt {
10    cipher: Aes128,
11}
12
13impl Ipcrypt {
14    /// The number of bytes required for the encryption key.
15    pub const KEY_BYTES: usize = 16;
16
17    /// Generates a new random key for encryption.
18    pub fn generate_key() -> [u8; Self::KEY_BYTES] {
19        rand::random()
20    }
21
22    /// Creates a new Ipcrypt instance with the given key.
23    ///
24    /// # Arguments
25    ///
26    /// * `key` - A 16-byte array containing the encryption key.
27    pub fn new(key: [u8; Self::KEY_BYTES]) -> Self {
28        let cipher = Aes128::new_from_slice(&key).expect("key length is guaranteed to be correct");
29        Self { cipher }
30    }
31
32    /// Creates a new Ipcrypt instance with a random key.
33    pub fn new_random() -> Self {
34        Self::new(Self::generate_key())
35    }
36
37    /// Encrypts a 16-byte IP address in place.
38    pub fn encrypt_ip16(&self, ip: &mut [u8; 16]) {
39        let mut block = Block::from(*ip);
40        self.cipher.encrypt_block(&mut block);
41        *ip = block.into();
42    }
43
44    /// Decrypts a 16-byte IP address in place.
45    pub fn decrypt_ip16(&self, ip: &mut [u8; 16]) {
46        let mut block = Block::from(*ip);
47        self.cipher.decrypt_block(&mut block);
48        *ip = block.into();
49    }
50
51    /// Encrypts an IP address.
52    ///
53    /// # Arguments
54    ///
55    /// * `ip` - The IP address to encrypt
56    ///
57    /// # Returns
58    /// The encrypted IP address
59    pub fn encrypt_ipaddr(&self, ip: IpAddr) -> IpAddr {
60        let mut bytes = ip_to_bytes(ip);
61        self.encrypt_ip16(&mut bytes);
62        bytes_to_ip(bytes)
63    }
64
65    /// Decrypts an IP address.
66    ///
67    /// # Arguments
68    ///
69    /// * `encrypted` - The encrypted IP address
70    ///
71    /// # Returns
72    /// The decrypted IP address
73    pub fn decrypt_ipaddr(&self, encrypted: IpAddr) -> IpAddr {
74        let mut bytes = ip_to_bytes(encrypted);
75        self.decrypt_ip16(&mut bytes);
76        bytes_to_ip(bytes)
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use ct_codecs::{Decoder as _, Hex};
84    use std::str::FromStr;
85
86    #[test]
87    fn test_deterministic_vectors() {
88        let test_vectors = vec![
89            (
90                // Test vector 1
91                "0123456789abcdeffedcba9876543210",
92                "0.0.0.0",
93                "bde9:6789:d353:824c:d7c6:f58a:6bd2:26eb",
94            ),
95            (
96                // Test vector 2
97                "1032547698badcfeefcdab8967452301",
98                "255.255.255.255",
99                "aed2:92f6:ea23:58c3:48fd:8b8:74e8:45d8",
100            ),
101            (
102                // Test vector 3
103                "2b7e151628aed2a6abf7158809cf4f3c",
104                "192.0.2.1",
105                "1dbd:c1b9:fff1:7586:7d0b:67b4:e76e:4777",
106            ),
107        ];
108
109        for (key_hex, input_ip, expected_output) in test_vectors {
110            // Parse key using constant-time hex decoder
111            let key_vec = Hex::decode_to_vec(key_hex.as_bytes(), None).unwrap();
112            let mut key = [0u8; Ipcrypt::KEY_BYTES];
113            key.copy_from_slice(&key_vec);
114
115            // Create Ipcrypt instance
116            let ipcrypt = Ipcrypt::new(key);
117
118            // Parse input IP
119            let ip = IpAddr::from_str(input_ip).unwrap();
120
121            // Encrypt
122            let encrypted = ipcrypt.encrypt_ipaddr(ip);
123            assert_eq!(encrypted.to_string(), expected_output);
124
125            // Decrypt
126            let decrypted = ipcrypt.decrypt_ipaddr(encrypted);
127            assert_eq!(decrypted, ip);
128        }
129    }
130
131    #[test]
132    fn test_random_key() {
133        let ipcrypt = Ipcrypt::new_random();
134        let ip = IpAddr::from_str("192.0.2.1").unwrap();
135        let encrypted = ipcrypt.encrypt_ipaddr(ip);
136        let decrypted = ipcrypt.decrypt_ipaddr(encrypted);
137        assert_eq!(ip, decrypted);
138    }
139}