From 7340db926e570b4d6cf8bfd654dc60747349a2de Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Mon, 16 Mar 2015 09:33:01 -0400 Subject: also implement encrypting in cbc mode --- src/aes.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'src/aes.rs') diff --git a/src/aes.rs b/src/aes.rs index 3ff9850..eb281e2 100644 --- a/src/aes.rs +++ b/src/aes.rs @@ -28,6 +28,30 @@ pub fn decrypt_aes_128_cbc (bytes: &[u8], key: &[u8], iv: &[u8]) -> Vec { return unpad_pkcs7(&plaintext[..]).to_vec(); } +pub fn encrypt_aes_128_ecb (bytes: &[u8], key: &[u8]) -> Vec { + return openssl::crypto::symm::encrypt( + openssl::crypto::symm::Type::AES_128_ECB, + key, + vec![], + bytes + ) +} + +pub fn encrypt_aes_128_cbc (bytes: &[u8], key: &[u8], iv: &[u8]) -> Vec { + let mut prev = iv.to_vec(); + let mut ciphertext = vec![]; + for block in bytes.chunks(16) { + let plaintext_block = fixed_xor(&pad_pkcs7(block, 16)[..], &prev[..]); + let mut ciphertext_block = encrypt_aes_128_ecb(&plaintext_block[..], key); + ciphertext_block.truncate(16); + for &c in ciphertext_block.iter() { + ciphertext.push(c); + } + prev = ciphertext_block.clone(); + } + return ciphertext; +} + pub fn find_aes_128_ecb_encrypted_string (inputs: &[Vec]) -> Vec { let mut max_dups = 0; let mut found = vec![]; @@ -46,3 +70,26 @@ pub fn find_aes_128_ecb_encrypted_string (inputs: &[Vec]) -> Vec { } return found; } + +#[test] +fn test_encrypt_decrypt () { + let plaintext = b"Summertime and the wind is blowing outside in lower \ + Chelsea and I don't know what I'm doing in the city, the \ + sun is always in my eyes"; + let key = b"YELLOW SUBMARINE"; + let iv = [0; 16]; + + let ciphertext_ecb = encrypt_aes_128_ecb(&plaintext[..], &key[..]); + let ciphertext_cbc = encrypt_aes_128_cbc(&plaintext[..], &key[..], &iv[..]); + + let plaintext2_ecb = decrypt_aes_128_ecb(&ciphertext_ecb[..], &key[..]); + let plaintext2_cbc = decrypt_aes_128_cbc(&ciphertext_cbc[..], &key[..], &iv[..]); + + let ciphertext2_ecb = encrypt_aes_128_ecb(&plaintext2_ecb[..], &key[..]); + let ciphertext2_cbc = encrypt_aes_128_cbc(&plaintext2_cbc[..], &key[..], &iv[..]); + + assert_eq!(plaintext, plaintext2_ecb); + assert_eq!(plaintext, plaintext2_cbc); + assert_eq!(ciphertext_ecb, ciphertext2_ecb); + assert_eq!(ciphertext_cbc, ciphertext2_cbc); +} -- cgit v1.2.3-54-g00ecf