X-Git-Url: http://git.euphorik.ch/?p=rup.git;a=blobdiff_plain;f=src%2Fcrypto.rs;h=cc8bf848ef326a615dadf4023f278b47cc86fb3d;hp=6d791eb0f56a437288a3e0780585a4558fc0cdfa;hb=b1f2c5b803a7e85a3b0c8d999cf9a13d28c6c6c2;hpb=98687ed0454061c7164ab64e8bd5d25b18896a39 diff --git a/src/crypto.rs b/src/crypto.rs index 6d791eb..cc8bf84 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -1,14 +1,38 @@ +use openssl::{symm, sha::sha256}; +use rand::prelude::*; +/// Encrypt the given text with the given key. The key length must be 128 bits encoded in base64. +/// Ouput format: +/// Format "1" + base_64( + + ) +/// IV: 16 bytes randomized. +/// Mode : CBC. pub fn encrypt(key: &str, plain_text: &str) -> String { - let key_as_bytes = base64::decode(key); + let key_as_bytes = base64::decode(key).expect("Unable to decode base64 encoded key"); + assert!(key_as_bytes.len() == 16); + let text_as_bytes = plain_text.as_bytes(); + let iv = rand::thread_rng().gen::<[u8; 16]>(); - String::new() + let cipher_text = + symm::encrypt(symm::Cipher::aes_128_cbc(), &key_as_bytes, Some(&iv), text_as_bytes) + .expect("Unable to encrypt message"); + + let hash_text = sha256(&text_as_bytes); + + let mut result: Vec = Vec::new(); + result.extend(&iv); + result.extend(&hash_text); + result.extend(&cipher_text); + + String::from("1") + &base64::encode(&result) } -pub fn decrypt(key: &str, cypher_text: &str) -> Option { +pub fn decrypt(key: &str, cipher_text: &str) -> Option { + if cipher_text.chars() != '1' { + return None; + } - println!("cypher: {}", cypher_text); + println!("cypher: {}", cipher_text); Some(String::new()) }