21 lines
812 B
Rust
21 lines
812 B
Rust
|
use std::error::Error;
|
||
|
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
|
||
|
use aes_gcm::aead::{Aead, Payload};
|
||
|
use crate::config::TFConfig;
|
||
|
|
||
|
pub fn get_cipher_from_config(config: &TFConfig) -> Result<Aes256Gcm, Box<dyn Error>> {
|
||
|
let key_slice = hex::decode(&config.data_key)?;
|
||
|
Ok(Aes256Gcm::new_from_slice(&key_slice)?)
|
||
|
}
|
||
|
|
||
|
pub fn encrypt_with_nonce(plaintext: &[u8], nonce: [u8; 12], cipher: &Aes256Gcm) -> Result<Vec<u8>, aes_gcm::Error> {
|
||
|
let nonce = Nonce::from_slice(&nonce);
|
||
|
let ciphertext = cipher.encrypt(nonce, plaintext)?;
|
||
|
Ok(ciphertext)
|
||
|
}
|
||
|
|
||
|
pub fn decrypt_with_nonce(ciphertext: &[u8], nonce: [u8; 12], cipher: &Aes256Gcm) -> Result<Vec<u8>, aes_gcm::Error> {
|
||
|
let nonce = Nonce::from_slice(&nonce);
|
||
|
let plaintext = cipher.decrypt(nonce, Payload::from(ciphertext))?;
|
||
|
Ok(plaintext)
|
||
|
}
|