cc8bf848ef326a615dadf4023f278b47cc86fb3d
[rup.git] / src / crypto.rs
1 use openssl::{symm, sha::sha256};
2 use rand::prelude::*;
3
4 /// Encrypt the given text with the given key. The key length must be 128 bits encoded in base64.
5 /// Ouput format:
6 /// Format "1" + base_64(<IV> + <hash(message)> + <aes(message)>)
7 /// IV: 16 bytes randomized.
8 /// Mode : CBC.
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);
12
13 let text_as_bytes = plain_text.as_bytes();
14
15 let iv = rand::thread_rng().gen::<[u8; 16]>();
16
17 let cipher_text =
18 symm::encrypt(symm::Cipher::aes_128_cbc(), &key_as_bytes, Some(&iv), text_as_bytes)
19 .expect("Unable to encrypt message");
20
21 let hash_text = sha256(&text_as_bytes);
22
23 let mut result: Vec<u8> = Vec::new();
24 result.extend(&iv);
25 result.extend(&hash_text);
26 result.extend(&cipher_text);
27
28 String::from("1") + &base64::encode(&result)
29 }
30
31 pub fn decrypt(key: &str, cipher_text: &str) -> Option<String> {
32 if cipher_text.chars() != '1' {
33 return None;
34 }
35
36 println!("cypher: {}", cipher_text);
37 Some(String::new())
38 }