Skip to content

Commit

Permalink
Create encryption.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Dec 8, 2024
1 parent ef93adb commit 72f0945
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/security/encryption.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use aes_gcm::{Aes128Gcm, Key, Nonce};
use rand::Rng;

pub fn encrypt(data: &[u8], key: &[u8]) -> Vec<u8> {
let cipher = Aes128Gcm::new(Key::from_slice(key));
let nonce = rand::thread_rng().gen::<Nonce>();
let encrypted_data = cipher.encrypt(nonce, data).unwrap();
let mut result = Vec::new();
result.extend_from_slice(&nonce);
result.extend_from_slice(&encrypted_data);
result
}

pub fn decrypt(data: &[u8], key: &[u8]) -> Vec<u8> {
let cipher = Aes128Gcm::new(Key::from_slice(key));
let nonce = Nonce::from_slice(&data[..12]);
let encrypted_data = &data[12..];
cipher.decrypt(nonce, encrypted_data).unwrap()
}

0 comments on commit 72f0945

Please sign in to comment.