cc8bf848ef326a615dadf4023f278b47cc86fb3d
1 use openssl
::{symm
, sha
::sha256
};
4 /// Encrypt the given text with the given key. The key length must be 128 bits encoded in base64.
6 /// Format "1" + base_64(<IV> + <hash(message)> + <aes(message)>)
7 /// IV: 16 bytes randomized.
9 pub fn encrypt(key
: &str, plain_text
: &str) -> String
{
10 let key_as_bytes
= base64
::decode(key
).expect("Unable to decode base64 encoded key");
11 assert!(key_as_bytes
.len() == 16);
13 let text_as_bytes
= plain_text
.as_bytes();
15 let iv
= rand
::thread_rng().gen
::<[u8; 16]>();
18 symm
::encrypt(symm
::Cipher
::aes_128_cbc(), &key_as_bytes
, Some(&iv
), text_as_bytes
)
19 .expect("Unable to encrypt message");
21 let hash_text
= sha256(&text_as_bytes
);
23 let mut result
: Vec
<u8> = Vec
::new();
25 result
.extend(&hash_text
);
26 result
.extend(&cipher_text
);
28 String
::from("1") + &base64
::encode(&result
)
31 pub fn decrypt(key
: &str, cipher_text
: &str) -> Option
<String
> {
32 if cipher_text
.chars() != '
1'
{
36 println!("cypher: {}", cipher_text
);