2024-03-21 20:07:56 +01:00

177 lines
5.7 KiB
Rust

/* This module is temporary. We'll use the module described in key_encription
module defined in sdk_common repository! Some of the methods there were copied here.
*/
use wasm_bindgen::JsValue;
use web_sys::console;
use core::result::Result as CoreResult;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use aes::cipher::consts::U32;
use aes::cipher::generic_array::GenericArray;
use aes_gcm::{
aead::{AeadInPlace, KeyInit},
Aes256Gcm,
};
use rand::rngs::OsRng;
use hex;
use hex::FromHexError;
pub struct Aes256GcmIv96Bit {
pub key: GenericArray<u8, U32>,
}
impl Aes256GcmIv96Bit {
pub fn new() -> Self {
let mut key_bytes = [0u8; 32];
OsRng.fill_bytes(&mut key_bytes);
let key = GenericArray::from_slice(&key_bytes);
Aes256GcmIv96Bit { key: key.clone() }
}
pub fn encrypt(&self, data: &[u8]) -> CoreResult<Vec<u8>, aes_gcm::Error> {
let cipher = Aes256Gcm::new(&self.key);
let mut nonce = [0u8; 12];
OsRng.fill_bytes(&mut nonce);
let mut buffer = data.to_vec();
cipher.encrypt_in_place(GenericArray::from_slice(&nonce), b"", &mut buffer)?;
Ok([nonce.to_vec(), buffer].concat())
}
pub fn decrypt(&self, data: &[u8]) -> CoreResult<Vec<u8>, aes_gcm::Error> {
if data.len() < 12 {
return Err(aes_gcm::Error); // Remplacer par une erreur appropriée
}
let (nonce, encrypted_data) = data.split_at(12);
let mut buffer = encrypted_data.to_vec();
let cipher = Aes256Gcm::new(&self.key);
cipher.decrypt_in_place(GenericArray::from_slice(nonce), b"", &mut buffer)?;
Ok(buffer)
}
pub fn encrypt_string(&self, data: &str) -> CoreResult<String, String> {
match self.encrypt(data.as_bytes()) {
Ok(encrypted_data) => Ok(base64::encode(encrypted_data)),
Err(_) => Err("Erreur de chiffrement".to_string()),
}
}
pub fn decrypt_string(&self, data: &str) -> CoreResult<String, String> {
let decoded_data = match base64::decode(data) {
Ok(data) => data,
Err(_) => return Err("Erreur de décodage Base64".to_string()),
};
match self.decrypt(&decoded_data) {
Ok(decrypted_data) => match String::from_utf8(decrypted_data) {
Ok(text) => Ok(text),
Err(_) => Err("Erreur de conversion UTF-8".to_string()),
},
Err(_) => Err("Erreur de déchiffrement".to_string()),
}
}
pub fn export_key(&self) -> String {
base64::encode(&self.key)
}
pub fn import_key(encoded_key: &str) -> CoreResult<Self, String> {
match base64::decode(encoded_key) {
Ok(decoded_key) => {
if decoded_key.len() == 32 {
let key = GenericArray::from_slice(&decoded_key);
Ok(Aes256GcmIv96Bit { key: key.clone() })
} else {
Err("La taille de la clé n'est pas valide".to_string())
}
}
Err(_) => Err("Échec du décodage de la clé".to_string()),
}
}
}
#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct KeyEncryption {
pub attribute_name: Option<String>,
pub key: Option<String>,
pub algorithm: Option<String>,
}
impl KeyEncryption {
pub fn new(
attribute_name: Option<String>,
key: Option<String>,
algorithm: Option<String>,
) -> Self {
KeyEncryption {
attribute_name,
key,
algorithm,
}
}
pub fn encode(&self, data: String) -> CoreResult<String, String> {
if let Some(ref key) = self.key {
let decoded_key = Aes256GcmIv96Bit::import_key(key)?;
let encrypted_data = decoded_key.encrypt_string(&data)?;
Ok(encrypted_data)
} else {
Err("Aucune clé n'est définie".to_string())
}
}
pub fn decode(&self, encrypted_data: String) -> CoreResult<String, String> {
if let Some(ref key) = self.key {
let decoded_key = Aes256GcmIv96Bit::import_key(key)?;
let decrypted_data = decoded_key.decrypt_string(&encrypted_data)?;
Ok(decrypted_data)
} else {
Err("Aucune clé n'est définie".to_string())
}
}
pub fn enc(&self, data: Value) -> String {
let data_string = serde_json::to_string(&data).unwrap_or_else(|_| "".to_string());
self.encode(data_string).unwrap_or_else(|_| "".to_string())
}
pub fn enc_string(&self, data: String) -> String {
self.enc(Value::String(data))
}
pub fn enc_i64(&self, data: i64) -> String {
self.enc(Value::Number(data.into()))
}
pub fn enc_u64(&self, data: u64) -> String {
self.enc(Value::Number(data.into()))
}
pub fn enc_u32(&self, data: u32) -> String {
self.enc(Value::Number(data.into()))
}
pub fn enc_vec_string(&self, list: Vec<String>) -> String {
self.enc(Value::Array(list.into_iter().map(Value::String).collect()))
}
pub fn enc_vec_key_encryption(&self, list: Vec<KeyEncryption>) -> String {
// Utilisez `serde_json::to_value` pour convertir chaque `KeyEncryption` en `Value`
let json_list: Vec<Value> = list
.into_iter()
.map(|key_enc| serde_json::to_value(key_enc).unwrap_or_else(|_| json!({})))
.collect();
self.enc(Value::Array(json_list))
}
}
fn hex_to_generic_array(hex_string: &str) -> Result<GenericArray<u8, U32>, FromHexError> {
let byte_vec = hex::decode(hex_string)?;
let array = GenericArray::clone_from_slice(&byte_vec[..32]);
Ok(array)
}