teaql_tool_extra/
crypto.rs1use aes_gcm::{
2 aead::{Aead, AeadCore, KeyInit, OsRng},
3 Aes256Gcm, Key, Nonce
4};
5use teaql_tool_core::{Result, TeaQLToolError};
6
7pub struct CryptoTool;
8
9impl CryptoTool {
10 pub fn new() -> Self {
11 Self
12 }
13
14 pub fn generate_key(&self) -> Vec<u8> {
15 Aes256Gcm::generate_key(OsRng).to_vec()
16 }
17
18 pub fn encrypt(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
19 let key = Key::<Aes256Gcm>::from_slice(key);
20 let cipher = Aes256Gcm::new(key);
21 let nonce = Aes256Gcm::generate_nonce(&mut OsRng); let encrypted = cipher.encrypt(&nonce, data).map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
24
25 let mut result = nonce.to_vec();
27 result.extend_from_slice(&encrypted);
28 Ok(result)
29 }
30
31 pub fn decrypt(&self, encrypted_data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
32 if encrypted_data.len() < 12 {
33 return Err(TeaQLToolError::InvalidArgument("Invalid encrypted data length".to_string()));
34 }
35 let key = Key::<Aes256Gcm>::from_slice(key);
36 let cipher = Aes256Gcm::new(key);
37
38 let nonce = Nonce::from_slice(&encrypted_data[0..12]);
39 let ciphertext = &encrypted_data[12..];
40
41 cipher.decrypt(nonce, ciphertext).map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))
42 }
43}
44
45impl Default for CryptoTool {
46 fn default() -> Self {
47 Self::new()
48 }
49}