1 use openssl
::{symm
, sha
::sha256
};
8 UnableToDecodeBase64Key
,
13 pub enum EncryptError
{
19 pub enum DecryptError
{
22 UnableToDecodeBase64Message
,
24 UnableToDecodeMessageAsUTF8String
,
28 fn decode_key(key
: &str) -> Result
<Vec
<u8>, KeyError
> {
29 match base64
::decode(key
) {
30 Ok(k
) => if k
.len() != 16 { return Err(KeyError
::WrongKeyLength
) } else { Ok(k
) },
31 Err(_e
) => Err(KeyError
::UnableToDecodeBase64Key
)
35 /// Encrypt the given text with the given key. The key length must be 128 bits encoded in base64.
36 /// Ouput format: "1" + base_64(<IV> + <hash(message)> + <aes(message)>)
37 /// IV: 16 bytes randomized.
39 pub fn encrypt(key
: &str, plain_text
: &str) -> Result
<String
, EncryptError
> {
40 let key_as_bytes
= decode_key(key
).map_err(|e
| EncryptError
::KeyError(e
))?
;
42 let text_as_bytes
= plain_text
.as_bytes();
43 let iv
= rand
::thread_rng().gen
::<[u8; 16]>();
46 match symm
::encrypt(symm
::Cipher
::aes_128_cbc(), &key_as_bytes
, Some(&iv
), text_as_bytes
) {
48 Err(_e
) => return Err(EncryptError
::UnableToEncrypt
)
51 let hash_text
= sha256(&text_as_bytes
);
53 let mut result
: Vec
<u8> = Vec
::new();
55 result
.extend(&hash_text
);
56 result
.extend(&cipher_text
);
58 Ok(String
::from("1") + &base64
::encode(&result
))
61 /// Decrypt the given text with the given key. The key length must be 128 bits encoded in base64.
62 /// Input format: "1" + base_64(<IV> + <hash(message)> + <aes(message)>)
63 pub fn decrypt(key
: &str, cipher_text
: &str) -> Result
<String
, DecryptError
> {
64 let key_as_bytes
= decode_key(key
).map_err(|e
| DecryptError
::KeyError(e
))?
;
66 // Can't decrypt a message with the wrong version.
67 if !cipher_text
.starts_with(consts
::CURRENT_MESSAGE_VERSION
) { return Err(DecryptError
::WrongMessageVersion
) }
69 let cipher_text_bytes
=
70 base64
::decode(&cipher_text
.as_bytes()[consts
::CURRENT_MESSAGE_VERSION
.as_bytes().len()..])
71 .map_err(|_e
| DecryptError
::UnableToDecodeBase64Message
)?
;
73 let iv
= &cipher_text_bytes
[0..16];
74 let hash
= &cipher_text_bytes
[16..48];
75 let encrypted_message
= &cipher_text_bytes
[48..];
77 let plain_message_bytes
=
78 symm
::decrypt(symm
::Cipher
::aes_128_cbc(), &key_as_bytes
, Some(iv
), encrypted_message
)
79 .map_err(|_e
| DecryptError
::UnableToDecrypt
)?
;
81 if sha256(&plain_message_bytes
) != hash
{ return Err(DecryptError
::HashMismatch
) }
84 String
::from_utf8(plain_message_bytes
)
85 .map_err(|_e
| DecryptError
::UnableToDecodeMessageAsUTF8String
)?
;