Begining of the machine oracle (work in progress..)
[crypto_lab1.git] / src / crypto.rs
index ce301ab..d9fe182 100644 (file)
@@ -5,23 +5,45 @@ use openssl::crypto::hash::SHA256;
 use openssl::crypto::hmac::HMAC;
 use openssl::crypto::symm;
 
+// These aren't the keys you're looking for.
 static KEY_A: &'static [u8] = [125, 31, 131, 118, 143, 180, 252, 53, 211, 217, 79, 240, 128, 91, 252, 87, 104, 236, 145, 198, 163, 203, 161, 12, 53, 56, 218, 40, 221, 95, 171, 140];
 static KEY_C: &'static [u8] = [75, 226, 88, 31, 223, 216, 182, 216, 178, 58, 59, 193, 245, 80, 254, 128, 125, 246, 246, 224, 194, 190, 123, 123, 10, 131, 217, 183, 112, 157, 166, 102];
 
+/// Only returns the first ten bytes.
 pub fn compute_mac(data: &[u8]) -> [u8, ..10] {
    let mut hmac = HMAC(SHA256, KEY_A);
    hmac.update(data);
    let mut result = [0u8, ..10];
-   copy_memory(&mut result, hmac.finalize().slice(0, 9));
+   copy_memory(&mut result, hmac.finalize().slice(0, 10));
    result
 }
 
-pub fn encrypt(plaindata: &[u8], iv: &[u8]) -> Vec<u8> {
-   symm::encrypt(symm::AES_256_CBC, KEY_C, iv.to_vec(), plaindata)
+/// Encrypt may fail if the provided data size isn't a multiple of 16.
+pub fn encrypt(plaindata: &[u8], iv: &[u8]) -> Option<Vec<u8>> {
+   let c = symm::Crypter::new(symm::AES_256_CBC);
+   c.init(symm::Encrypt, KEY_C, iv.to_vec());
+   c.pad(false); // Padding disabled!
+   let r = c.update(plaindata);
+   let rest = c.finalize();
+   if rest.is_empty() {
+      Some(r)
+   } else {
+      None
+   }
 }
 
-pub fn decrypt(cypherdata: &[u8], iv: &[u8]) -> Vec<u8> {
-   symm::decrypt(symm::AES_256_CBC, KEY_C, iv.to_vec(), cypherdata)
+/// Decrypt may fail if the provided data size isn't a multiple of 16.
+pub fn decrypt(cypherdata: &[u8], iv: &[u8]) -> Option<Vec<u8>> {
+   let c = symm::Crypter::new(symm::AES_256_CBC);
+   c.init(symm::Decrypt, KEY_C, iv.to_vec());
+   c.pad(false); // Padding disabled!
+   let r = c.update(cypherdata);
+   let rest = c.finalize();
+   if rest.is_empty() {
+      Some(r)
+   } else {
+      None
+   }
 }
 
 pub fn generate_key(size_byte: uint) -> IoResult<Vec<u8>>  {