X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=src%2Fcrypto.rs;h=caf34f7cd10b7f2f50ee10ea0e83cbd3416d1ed4;hb=f43bab0b61b36e53135569727476fc6f39a3deec;hp=7e707d02a218c64fc99034c8f1ac9205ccac0635;hpb=51aa7c917b3ecfb80d06d5a06cc9f553b8bc91c6;p=rup.git diff --git a/src/crypto.rs b/src/crypto.rs index 7e707d0..caf34f7 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -19,6 +19,7 @@ pub enum EncryptError { pub enum DecryptError { KeyError(KeyError), WrongMessageVersion, + MessageToShort, UnableToDecodeBase64Message, UnableToDecrypt, UnableToDecodeMessageAsUTF8String, @@ -27,27 +28,24 @@ pub enum DecryptError { fn decode_key(key: &str) -> Result, KeyError> { match base64::decode(key) { - Ok(k) => if k.len() != 16 { return Err(KeyError::WrongKeyLength) } else { Ok(k) }, + Ok(k) => if k.len() != 16 { Err(KeyError::WrongKeyLength) } else { Ok(k) }, Err(_e) => Err(KeyError::UnableToDecodeBase64Key) } } /// Encrypt the given text with the given key. The key length must be 128 bits encoded in base64. -/// Ouput format: -/// Format "1" + base_64( + + ) +/// Ouput format: "1" + base_64( + + ) /// IV: 16 bytes randomized. /// Mode : CBC. pub fn encrypt(key: &str, plain_text: &str) -> Result { - let key_as_bytes = decode_key(key).map_err(|e| EncryptError::KeyError(e))?; + let key_as_bytes = decode_key(key).map_err(EncryptError::KeyError)?; let text_as_bytes = plain_text.as_bytes(); let iv = rand::thread_rng().gen::<[u8; 16]>(); let cipher_text = - match symm::encrypt(symm::Cipher::aes_128_cbc(), &key_as_bytes, Some(&iv), text_as_bytes) { - Ok(t) => t, - Err(_e) => return Err(EncryptError::UnableToEncrypt) - }; + symm::encrypt(symm::Cipher::aes_128_cbc(), &key_as_bytes, Some(&iv), text_as_bytes) + .map_err(|_e| EncryptError::UnableToEncrypt)?; let hash_text = sha256(&text_as_bytes); @@ -59,9 +57,10 @@ pub fn encrypt(key: &str, plain_text: &str) -> Result { Ok(String::from("1") + &base64::encode(&result)) } -/// TODO: return a Result +/// Decrypt the given text with the given key. The key length must be 128 bits encoded in base64. +/// Input format: "1" + base_64( + + ) pub fn decrypt(key: &str, cipher_text: &str) -> Result { - let key_as_bytes = decode_key(key).map_err(|e| DecryptError::KeyError(e))?; + let key_as_bytes = decode_key(key).map_err(DecryptError::KeyError)?; // Can't decrypt a message with the wrong version. if !cipher_text.starts_with(consts::CURRENT_MESSAGE_VERSION) { return Err(DecryptError::WrongMessageVersion) } @@ -70,6 +69,8 @@ pub fn decrypt(key: &str, cipher_text: &str) -> Result { base64::decode(&cipher_text.as_bytes()[consts::CURRENT_MESSAGE_VERSION.as_bytes().len()..]) .map_err(|_e| DecryptError::UnableToDecodeBase64Message)?; + if cipher_text_bytes.len() <= 48 { return Err(DecryptError::MessageToShort) } + let iv = &cipher_text_bytes[0..16]; let hash = &cipher_text_bytes[16..48]; let encrypted_message = &cipher_text_bytes[48..];