1 //! Low level AES IGE and key wrapping functionality
2 //!
3 //! AES ECB, CBC, XTS, CTR, CFB, GCM and other conventional symmetric encryption
4 //! modes are found in [`symm`]. This is the implementation of AES IGE and key wrapping
5 //!
6 //! Advanced Encryption Standard (AES) provides symmetric key cipher that
7 //! the same key is used to encrypt and decrypt data. This implementation
8 //! uses 128, 192, or 256 bit keys. This module provides functions to
9 //! create a new key with [`new_encrypt`] and perform an encryption/decryption
10 //! using that key with [`aes_ige`].
11 //!
12 //! [`new_encrypt`]: struct.AesKey.html#method.new_encrypt
13 //! [`aes_ige`]: fn.aes_ige.html
14 //!
15 //! The [`symm`] module should be used in preference to this module in most cases.
16 //! The IGE block cypher is a non-traditional cipher mode. More traditional AES
17 //! encryption methods are found in the [`Crypter`] and [`Cipher`] structs.
18 //!
19 //! [`symm`]: ../symm/index.html
20 //! [`Crypter`]: ../symm/struct.Crypter.html
21 //! [`Cipher`]: ../symm/struct.Cipher.html
22 //!
23 //! # Examples
24 //!
25 //! ## AES IGE
26 //! ```rust
27 //! use openssl::aes::{AesKey, aes_ige};
28 //! use openssl::symm::Mode;
29 //!
30 //! let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F";
31 //! let plaintext = b"\x12\x34\x56\x78\x90\x12\x34\x56\x12\x34\x56\x78\x90\x12\x34\x56";
32 //! let mut iv = *b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\
33 //! \x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";
34 //!
35 //! let key = AesKey::new_encrypt(key).unwrap();
36 //! let mut output = [0u8; 16];
37 //! aes_ige(plaintext, &mut output, &key, &mut iv, Mode::Encrypt);
38 //! assert_eq!(output, *b"\xa6\xad\x97\x4d\x5c\xea\x1d\x36\xd2\xf3\x67\x98\x09\x07\xed\x32");
39 //! ```
40 //!
41 //! ## Key wrapping
42 //! ```rust
43 //! use openssl::aes::{AesKey, unwrap_key, wrap_key};
44 //!
45 //! let kek = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F";
46 //! let key_to_wrap = b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF";
47 //!
48 //! let enc_key = AesKey::new_encrypt(kek).unwrap();
49 //! let mut ciphertext = [0u8; 24];
50 //! wrap_key(&enc_key, None, &mut ciphertext, &key_to_wrap[..]).unwrap();
51 //! let dec_key = AesKey::new_decrypt(kek).unwrap();
52 //! let mut orig_key = [0u8; 16];
53 //! unwrap_key(&dec_key, None, &mut orig_key, &ciphertext[..]).unwrap();
54 //!
55 //! assert_eq!(&orig_key[..], &key_to_wrap[..]);
56 //! ```
57 //!
58 use libc::{c_int, c_uint};
59 use std::mem::MaybeUninit;
60 use std::ptr;
61
62 use crate::symm::Mode;
63
64 /// Provides Error handling for parsing keys.
65 #[derive(Debug)]
66 pub struct KeyError(());
67
68 /// The key used to encrypt or decrypt cipher blocks.
69 pub struct AesKey(ffi::AES_KEY);
70
71 impl AesKey {
72 /// Prepares a key for encryption.
73 ///
74 /// # Failure
75 ///
76 /// Returns an error if the key is not 128, 192, or 256 bits.
new_encrypt(key: &[u8]) -> Result<AesKey, KeyError>77 pub fn new_encrypt(key: &[u8]) -> Result<AesKey, KeyError> {
78 unsafe {
79 assert!(key.len() <= c_int::max_value() as usize / 8);
80
81 let mut aes_key = MaybeUninit::uninit();
82 let r = ffi::AES_set_encrypt_key(
83 key.as_ptr() as *const _,
84 key.len() as c_int * 8,
85 aes_key.as_mut_ptr(),
86 );
87 if r == 0 {
88 Ok(AesKey(aes_key.assume_init()))
89 } else {
90 Err(KeyError(()))
91 }
92 }
93 }
94
95 /// Prepares a key for decryption.
96 ///
97 /// # Failure
98 ///
99 /// Returns an error if the key is not 128, 192, or 256 bits.
new_decrypt(key: &[u8]) -> Result<AesKey, KeyError>100 pub fn new_decrypt(key: &[u8]) -> Result<AesKey, KeyError> {
101 unsafe {
102 assert!(key.len() <= c_int::max_value() as usize / 8);
103
104 let mut aes_key = MaybeUninit::uninit();
105 let r = ffi::AES_set_decrypt_key(
106 key.as_ptr() as *const _,
107 key.len() as c_int * 8,
108 aes_key.as_mut_ptr(),
109 );
110
111 if r == 0 {
112 Ok(AesKey(aes_key.assume_init()))
113 } else {
114 Err(KeyError(()))
115 }
116 }
117 }
118 }
119
120 /// Performs AES IGE encryption or decryption
121 ///
122 /// AES IGE (Infinite Garble Extension) is a form of AES block cipher utilized in
123 /// OpenSSL. Infinite Garble refers to propagating forward errors. IGE, like other
124 /// block ciphers implemented for AES requires an initialization vector. The IGE mode
125 /// allows a stream of blocks to be encrypted or decrypted without having the entire
126 /// plaintext available. For more information, visit [AES IGE Encryption].
127 ///
128 /// This block cipher uses 16 byte blocks. The rust implementation will panic
129 /// if the input or output does not meet this 16-byte boundary. Attention must
130 /// be made in this low level implementation to pad the value to the 128-bit boundary.
131 ///
132 /// [AES IGE Encryption]: http://www.links.org/files/openssl-ige.pdf
133 ///
134 /// # Panics
135 ///
136 /// Panics if `in_` is not the same length as `out`, if that length is not a multiple of 16, or if
137 /// `iv` is not at least 32 bytes.
aes_ige(in_: &[u8], out: &mut [u8], key: &AesKey, iv: &mut [u8], mode: Mode)138 pub fn aes_ige(in_: &[u8], out: &mut [u8], key: &AesKey, iv: &mut [u8], mode: Mode) {
139 unsafe {
140 assert!(in_.len() == out.len());
141 assert!(in_.len() % ffi::AES_BLOCK_SIZE as usize == 0);
142 assert!(iv.len() >= ffi::AES_BLOCK_SIZE as usize * 2);
143
144 let mode = match mode {
145 Mode::Encrypt => ffi::AES_ENCRYPT,
146 Mode::Decrypt => ffi::AES_DECRYPT,
147 };
148 ffi::AES_ige_encrypt(
149 in_.as_ptr() as *const _,
150 out.as_mut_ptr() as *mut _,
151 in_.len(),
152 &key.0,
153 iv.as_mut_ptr() as *mut _,
154 mode,
155 );
156 }
157 }
158
159 /// Wrap a key, according to [RFC 3394](https://tools.ietf.org/html/rfc3394)
160 ///
161 /// * `key`: The key-encrypting-key to use. Must be a encrypting key
162 /// * `iv`: The IV to use. You must use the same IV for both wrapping and unwrapping
163 /// * `out`: The output buffer to store the ciphertext
164 /// * `in_`: The input buffer, storing the key to be wrapped
165 ///
166 /// Returns the number of bytes written into `out`
167 ///
168 /// # Panics
169 ///
170 /// Panics if either `out` or `in_` do not have sizes that are a multiple of 8, or if
171 /// `out` is not 8 bytes longer than `in_`
wrap_key( key: &AesKey, iv: Option<[u8; 8]>, out: &mut [u8], in_: &[u8], ) -> Result<usize, KeyError>172 pub fn wrap_key(
173 key: &AesKey,
174 iv: Option<[u8; 8]>,
175 out: &mut [u8],
176 in_: &[u8],
177 ) -> Result<usize, KeyError> {
178 unsafe {
179 assert!(out.len() >= in_.len() + 8); // Ciphertext is 64 bits longer (see 2.2.1)
180
181 let written = ffi::AES_wrap_key(
182 &key.0 as *const _ as *mut _, // this is safe, the implementation only uses the key as a const pointer.
183 iv.as_ref()
184 .map_or(ptr::null(), |iv| iv.as_ptr() as *const _),
185 out.as_ptr() as *mut _,
186 in_.as_ptr() as *const _,
187 in_.len() as c_uint,
188 );
189 if written <= 0 {
190 Err(KeyError(()))
191 } else {
192 Ok(written as usize)
193 }
194 }
195 }
196
197 /// Unwrap a key, according to [RFC 3394](https://tools.ietf.org/html/rfc3394)
198 ///
199 /// * `key`: The key-encrypting-key to decrypt the wrapped key. Must be a decrypting key
200 /// * `iv`: The same IV used for wrapping the key
201 /// * `out`: The buffer to write the unwrapped key to
202 /// * `in_`: The input ciphertext
203 ///
204 /// Returns the number of bytes written into `out`
205 ///
206 /// # Panics
207 ///
208 /// Panics if either `out` or `in_` do not have sizes that are a multiple of 8, or
209 /// if `in_` is not 8 bytes longer than `out`
unwrap_key( key: &AesKey, iv: Option<[u8; 8]>, out: &mut [u8], in_: &[u8], ) -> Result<usize, KeyError>210 pub fn unwrap_key(
211 key: &AesKey,
212 iv: Option<[u8; 8]>,
213 out: &mut [u8],
214 in_: &[u8],
215 ) -> Result<usize, KeyError> {
216 unsafe {
217 assert!(out.len() + 8 <= in_.len());
218
219 let written = ffi::AES_unwrap_key(
220 &key.0 as *const _ as *mut _, // this is safe, the implementation only uses the key as a const pointer.
221 iv.as_ref()
222 .map_or(ptr::null(), |iv| iv.as_ptr() as *const _),
223 out.as_ptr() as *mut _,
224 in_.as_ptr() as *const _,
225 in_.len() as c_uint,
226 );
227
228 if written <= 0 {
229 Err(KeyError(()))
230 } else {
231 Ok(written as usize)
232 }
233 }
234 }
235
236 #[cfg(test)]
237 mod test {
238 use hex::FromHex;
239
240 use super::*;
241 use crate::symm::Mode;
242
243 // From https://www.mgp25.com/AESIGE/
244 #[test]
ige_vector_1()245 fn ige_vector_1() {
246 let raw_key = "000102030405060708090A0B0C0D0E0F";
247 let raw_iv = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
248 let raw_pt = "0000000000000000000000000000000000000000000000000000000000000000";
249 let raw_ct = "1A8519A6557BE652E9DA8E43DA4EF4453CF456B4CA488AA383C79C98B34797CB";
250
251 let key = AesKey::new_encrypt(&Vec::from_hex(raw_key).unwrap()).unwrap();
252 let mut iv = Vec::from_hex(raw_iv).unwrap();
253 let pt = Vec::from_hex(raw_pt).unwrap();
254 let ct = Vec::from_hex(raw_ct).unwrap();
255
256 let mut ct_actual = vec![0; ct.len()];
257 aes_ige(&pt, &mut ct_actual, &key, &mut iv, Mode::Encrypt);
258 assert_eq!(ct_actual, ct);
259
260 let key = AesKey::new_decrypt(&Vec::from_hex(raw_key).unwrap()).unwrap();
261 let mut iv = Vec::from_hex(raw_iv).unwrap();
262 let mut pt_actual = vec![0; pt.len()];
263 aes_ige(&ct, &mut pt_actual, &key, &mut iv, Mode::Decrypt);
264 assert_eq!(pt_actual, pt);
265 }
266
267 // from the RFC https://tools.ietf.org/html/rfc3394#section-2.2.3
268 #[test]
test_wrap_unwrap()269 fn test_wrap_unwrap() {
270 let raw_key = Vec::from_hex("000102030405060708090A0B0C0D0E0F").unwrap();
271 let key_data = Vec::from_hex("00112233445566778899AABBCCDDEEFF").unwrap();
272 let expected_ciphertext =
273 Vec::from_hex("1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5").unwrap();
274
275 let enc_key = AesKey::new_encrypt(&raw_key).unwrap();
276 let mut wrapped = [0; 24];
277 assert_eq!(
278 wrap_key(&enc_key, None, &mut wrapped, &key_data).unwrap(),
279 24
280 );
281 assert_eq!(&wrapped[..], &expected_ciphertext[..]);
282
283 let dec_key = AesKey::new_decrypt(&raw_key).unwrap();
284 let mut unwrapped = [0; 16];
285 assert_eq!(
286 unwrap_key(&dec_key, None, &mut unwrapped, &wrapped).unwrap(),
287 16
288 );
289 assert_eq!(&unwrapped[..], &key_data[..]);
290 }
291 }
292