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 ffi;
59 use libc::{c_int, c_uint};
60 use std::{mem, ptr};
61 
62 use 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.
77     #[allow(deprecated)] // https://github.com/rust-lang/rust/issues/63566
new_encrypt(key: &[u8]) -> Result<AesKey, KeyError>78     pub fn new_encrypt(key: &[u8]) -> Result<AesKey, KeyError> {
79         unsafe {
80             assert!(key.len() <= c_int::max_value() as usize / 8);
81 
82             let mut aes_key = mem::uninitialized();
83             let r = ffi::AES_set_encrypt_key(
84                 key.as_ptr() as *const _,
85                 key.len() as c_int * 8,
86                 &mut aes_key,
87             );
88             if r == 0 {
89                 Ok(AesKey(aes_key))
90             } else {
91                 Err(KeyError(()))
92             }
93         }
94     }
95 
96     /// Prepares a key for decryption.
97     ///
98     /// # Failure
99     ///
100     /// Returns an error if the key is not 128, 192, or 256 bits.
101     #[allow(deprecated)] // https://github.com/rust-lang/rust/issues/63566
new_decrypt(key: &[u8]) -> Result<AesKey, KeyError>102     pub fn new_decrypt(key: &[u8]) -> Result<AesKey, KeyError> {
103         unsafe {
104             assert!(key.len() <= c_int::max_value() as usize / 8);
105 
106             let mut aes_key = mem::uninitialized();
107             let r = ffi::AES_set_decrypt_key(
108                 key.as_ptr() as *const _,
109                 key.len() as c_int * 8,
110                 &mut aes_key,
111             );
112 
113             if r == 0 {
114                 Ok(AesKey(aes_key))
115             } else {
116                 Err(KeyError(()))
117             }
118         }
119     }
120 }
121 
122 /// Performs AES IGE encryption or decryption
123 ///
124 /// AES IGE (Infinite Garble Extension) is a form of AES block cipher utilized in
125 /// OpenSSL.  Infinite Garble referes to propogating forward errors.  IGE, like other
126 /// block ciphers implemented for AES requires an initalization vector.  The IGE mode
127 /// allows a stream of blocks to be encrypted or decrypted without having the entire
128 /// plaintext available.  For more information, visit [AES IGE Encryption].
129 ///
130 /// This block cipher uses 16 byte blocks.  The rust implmentation will panic
131 /// if the input or output does not meet this 16-byte boundry.  Attention must
132 /// be made in this low level implementation to pad the value to the 128-bit boundry.
133 ///
134 /// [AES IGE Encryption]: http://www.links.org/files/openssl-ige.pdf
135 ///
136 /// # Panics
137 ///
138 /// Panics if `in_` is not the same length as `out`, if that length is not a multiple of 16, or if
139 /// `iv` is not at least 32 bytes.
aes_ige(in_: &[u8], out: &mut [u8], key: &AesKey, iv: &mut [u8], mode: Mode)140 pub fn aes_ige(in_: &[u8], out: &mut [u8], key: &AesKey, iv: &mut [u8], mode: Mode) {
141     unsafe {
142         assert!(in_.len() == out.len());
143         assert!(in_.len() % ffi::AES_BLOCK_SIZE as usize == 0);
144         assert!(iv.len() >= ffi::AES_BLOCK_SIZE as usize * 2);
145 
146         let mode = match mode {
147             Mode::Encrypt => ffi::AES_ENCRYPT,
148             Mode::Decrypt => ffi::AES_DECRYPT,
149         };
150         ffi::AES_ige_encrypt(
151             in_.as_ptr() as *const _,
152             out.as_mut_ptr() as *mut _,
153             in_.len(),
154             &key.0,
155             iv.as_mut_ptr() as *mut _,
156             mode,
157         );
158     }
159 }
160 
161 /// Wrap a key, according to [RFC 3394](https://tools.ietf.org/html/rfc3394)
162 ///
163 /// * `key`: The key-encrypting-key to use. Must be a encrypting key
164 /// * `iv`: The IV to use. You must use the same IV for both wrapping and unwrapping
165 /// * `out`: The output buffer to store the ciphertext
166 /// * `in_`: The input buffer, storing the key to be wrapped
167 ///
168 /// Returns the number of bytes written into `out`
169 ///
170 /// # Panics
171 ///
172 /// Panics if either `out` or `in_` do not have sizes that are a multiple of 8, or if
173 /// `out` is not 8 bytes longer than `in_`
wrap_key( key: &AesKey, iv: Option<[u8; 8]>, out: &mut [u8], in_: &[u8], ) -> Result<usize, KeyError>174 pub fn wrap_key(
175     key: &AesKey,
176     iv: Option<[u8; 8]>,
177     out: &mut [u8],
178     in_: &[u8],
179 ) -> Result<usize, KeyError> {
180     unsafe {
181         assert!(out.len() >= in_.len() + 8); // Ciphertext is 64 bits longer (see 2.2.1)
182 
183         let written = ffi::AES_wrap_key(
184             &key.0 as *const _ as *mut _, // this is safe, the implementation only uses the key as a const pointer.
185             iv.as_ref()
186                 .map_or(ptr::null(), |iv| iv.as_ptr() as *const _),
187             out.as_ptr() as *mut _,
188             in_.as_ptr() as *const _,
189             in_.len() as c_uint,
190         );
191         if written <= 0 {
192             Err(KeyError(()))
193         } else {
194             Ok(written as usize)
195         }
196     }
197 }
198 
199 /// Unwrap a key, according to [RFC 3394](https://tools.ietf.org/html/rfc3394)
200 ///
201 /// * `key`: The key-encrypting-key to decrypt the wrapped key. Must be a decrypting key
202 /// * `iv`: The same IV used for wrapping the key
203 /// * `out`: The buffer to write the unwrapped key to
204 /// * `in_`: The input ciphertext
205 ///
206 /// Returns the number of bytes written into `out`
207 ///
208 /// # Panics
209 ///
210 /// Panics if either `out` or `in_` do not have sizes that are a multiple of 8, or
211 /// 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>212 pub fn unwrap_key(
213     key: &AesKey,
214     iv: Option<[u8; 8]>,
215     out: &mut [u8],
216     in_: &[u8],
217 ) -> Result<usize, KeyError> {
218     unsafe {
219         assert!(out.len() + 8 <= in_.len());
220 
221         let written = ffi::AES_unwrap_key(
222             &key.0 as *const _ as *mut _, // this is safe, the implementation only uses the key as a const pointer.
223             iv.as_ref()
224                 .map_or(ptr::null(), |iv| iv.as_ptr() as *const _),
225             out.as_ptr() as *mut _,
226             in_.as_ptr() as *const _,
227             in_.len() as c_uint,
228         );
229 
230         if written <= 0 {
231             Err(KeyError(()))
232         } else {
233             Ok(written as usize)
234         }
235     }
236 }
237 
238 #[cfg(test)]
239 mod test {
240     use hex::FromHex;
241 
242     use super::*;
243     use symm::Mode;
244 
245     // From https://www.mgp25.com/AESIGE/
246     #[test]
ige_vector_1()247     fn ige_vector_1() {
248         let raw_key = "000102030405060708090A0B0C0D0E0F";
249         let raw_iv = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
250         let raw_pt = "0000000000000000000000000000000000000000000000000000000000000000";
251         let raw_ct = "1A8519A6557BE652E9DA8E43DA4EF4453CF456B4CA488AA383C79C98B34797CB";
252 
253         let key = AesKey::new_encrypt(&Vec::from_hex(raw_key).unwrap()).unwrap();
254         let mut iv = Vec::from_hex(raw_iv).unwrap();
255         let pt = Vec::from_hex(raw_pt).unwrap();
256         let ct = Vec::from_hex(raw_ct).unwrap();
257 
258         let mut ct_actual = vec![0; ct.len()];
259         aes_ige(&pt, &mut ct_actual, &key, &mut iv, Mode::Encrypt);
260         assert_eq!(ct_actual, ct);
261 
262         let key = AesKey::new_decrypt(&Vec::from_hex(raw_key).unwrap()).unwrap();
263         let mut iv = Vec::from_hex(raw_iv).unwrap();
264         let mut pt_actual = vec![0; pt.len()];
265         aes_ige(&ct, &mut pt_actual, &key, &mut iv, Mode::Decrypt);
266         assert_eq!(pt_actual, pt);
267     }
268 
269     // from the RFC https://tools.ietf.org/html/rfc3394#section-2.2.3
270     #[test]
test_wrap_unwrap()271     fn test_wrap_unwrap() {
272         let raw_key = Vec::from_hex("000102030405060708090A0B0C0D0E0F").unwrap();
273         let key_data = Vec::from_hex("00112233445566778899AABBCCDDEEFF").unwrap();
274         let expected_ciphertext =
275             Vec::from_hex("1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5").unwrap();
276 
277         let enc_key = AesKey::new_encrypt(&raw_key).unwrap();
278         let mut wrapped = [0; 24];
279         assert_eq!(
280             wrap_key(&enc_key, None, &mut wrapped, &key_data).unwrap(),
281             24
282         );
283         assert_eq!(&wrapped[..], &expected_ciphertext[..]);
284 
285         let dec_key = AesKey::new_decrypt(&raw_key).unwrap();
286         let mut unwrapped = [0; 16];
287         assert_eq!(
288             unwrap_key(&dec_key, None, &mut unwrapped, &wrapped).unwrap(),
289             16
290         );
291         assert_eq!(&unwrapped[..], &key_data[..]);
292     }
293 }
294