X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=src%2Fcrypto.rs;h=ddf257cd3b60d425a856792b4c10537ae86d4d5d;hb=96a5780355820bb1a78cb4ec8dff41dd30ef6ceb;hp=7e707d02a218c64fc99034c8f1ac9205ccac0635;hpb=51aa7c917b3ecfb80d06d5a06cc9f553b8bc91c6;p=rup.git diff --git a/src/crypto.rs b/src/crypto.rs index 7e707d0..ddf257c 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -27,27 +27,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 +56,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) }