diff options
author | Katharina Fey <kookie@spacekookie.de> | 2017-12-22 16:12:10 +0100 |
---|---|---|
committer | Katharina Fey <kookie@spacekookie.de> | 2017-12-22 16:12:10 +0100 |
commit | 4a9a899b6e6c587ab08314af66cf45582bb3c32e (patch) | |
tree | 70ff7c5295c35e5fb7bc629e6f95879d2f7539fe /src/security/encryption.rs | |
parent | 796ed122804424b9e0c3694adc6fc5712733b392 (diff) |
I think this is a lot nicer, don't you think?
Diffstat (limited to '')
-rw-r--r-- | src/security/encryption.rs | 41 |
1 files changed, 32 insertions, 9 deletions
diff --git a/src/security/encryption.rs b/src/security/encryption.rs index 8b9717b..aaa10ec 100644 --- a/src/security/encryption.rs +++ b/src/security/encryption.rs @@ -14,16 +14,36 @@ use generic_array::GenericArray; use std::str::from_utf8_unchecked; -// TODO: Use this implementation -pub trait Encryption { - fn encrypt(&self, data: &Vec<u8>) -> Vec<u8>; - fn decrypt(&self, data: &Vec<u8>) -> Vec<u8>; +pub trait Blaaaaaa<T: Serialize + Deserialize<'static>> { + fn encrypt(&self, data: &T) -> String; + fn decrypt(&self, data: &String) -> T; } /// Wraps high-level utilities pub struct CryptoHandler { - pub core: AES, + core: AES, +} + +impl<T: Serialize + Deserialize<'static>> Blaaaaaa<T> for CryptoHandler { + fn encrypt(&self, data: &T) -> String { + let encoded = serde_json::to_string(&data).unwrap(); + let vec = str_to_vec(&encoded); + + /* ✨ M A G I C ✨ */ + let encrypted = self.core.encrypt(&vec); + let base64 = encoding::base64_encode(&encrypted); + + return base64.to_owned(); + } + + fn decrypt(&self, data: &String) -> T { + let decoded = encoding::base64_decode(data); + let decrypted = self.core.decrypt(&decoded); + + let data: T = serde_json::from_str(&decrypted).unwrap(); + return data; + } } impl CryptoHandler { @@ -50,9 +70,9 @@ fn str_to_vec(string: &str) -> Vec<u8> { } -/// Generic encryption utility which takes any serialisable data +/// Generic encryption utility which takes any serialisable data /// and returns a base64 encoded ciphertext -/// +/// pub fn encrypt<T: Serialize>(handle: &CryptoHandler, data: T) -> String { let encoded = serde_json::to_string(&data).unwrap(); let vec = str_to_vec(&encoded); @@ -67,8 +87,11 @@ pub fn encrypt<T: Serialize>(handle: &CryptoHandler, data: T) -> String { /// Generic decryption utility which takes a base64 encoded ciphertext and /// returns any Deserializable Rust struct -/// -pub fn decrypt<T: Deserialize<'static>>(handle: &CryptoHandler, encrypted: &String) -> Result<T, ErrorType> { +/// +pub fn decrypt<T: Deserialize<'static>>( + handle: &CryptoHandler, + encrypted: &String, +) -> Result<T, ErrorType> { let decoded = encoding::base64_decode(encrypted); let decrypted = handle.core.decrypt(&decoded); |