Skip to content

Commit

Permalink
+ aes encrypt,de
Browse files Browse the repository at this point in the history
  • Loading branch information
haxjump committed Oct 31, 2024
1 parent bd878fd commit a961c2b
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 7 deletions.
24 changes: 17 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ruc"
version = "7.7.3"
version = "7.8.0"
authors = ["[email protected]"]
edition = "2021"
description = "Rust Util Collections"
Expand All @@ -19,10 +19,11 @@ sha3 = { version = "0.10.8", optional = true }
ed25519-zebra = { version = "4.0.0", optional = true }

rand = { version = "0.8", optional = true }
base64 = {version = "0.22.1", optional = true }
hex = {version = "0.4.3", optional = true }
base64 = { version = "0.22.1", optional = true }
hex = { version = "0.4.3", optional = true }

flate2 = {version = "1.0.34", optional = true }
flate2 = { version = "1.0.34", optional = true }
aes-gcm = { version = "0.10.3", optional = true }

time = { version = "0.3", features = ["formatting"] }
nix = { version = "0.29", features = ["socket"], optional = true }
Expand All @@ -49,14 +50,23 @@ ssh = [ "ssh2" ]
http = [ "reqwest" ]

algo = [
"algo_hash",
"algo_crypto",
"algo_rand",
"algo_hash",
]

algo_crypto = [
"ed25519-zebra",
"ende_base64",
"ende_hex",
"aes-gcm",
"algo_hash"
]
algo_rand = [
"rand",
"ende_hex"
]
algo_hash = [ "sha3" ]
algo_rand = [ "rand", "ende_hex" ]
algo_crypto = [ "ed25519-zebra", "ende_base64", "ende_hex" ]

ende = [
"ende_hex",
Expand Down
39 changes: 39 additions & 0 deletions src/algo/crypto/aes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use crate::{algo::hash::keccak, *};
use aes_gcm::{
aead::{Aead, KeyInit},
Aes256Gcm, Nonce,
};

pub fn encrypt(password: &str, contents: &[u8]) -> Result<Vec<u8>> {
let key_bytes = keccak::hash(password.as_bytes());
Aes256Gcm::new((&key_bytes).into())
.encrypt(&Nonce::default(), contents)
.map_err(|e| eg!(e))
}

pub fn decrypt(password: &str, encrypted_bytes: &[u8]) -> Result<Vec<u8>> {
let key_bytes = keccak::hash(password.as_bytes());
Aes256Gcm::new((&key_bytes).into())
.decrypt(&Nonce::default(), encrypted_bytes)
.map_err(|e| eg!(e))
}

#[cfg(test)]
mod test {
use super::*;
use crate::ende::base64;

#[test]
fn t_aec_gcm() {
for i in 11_u128..1111 {
let password = i.to_string();
let contents = base64::encode(keccak::hash(password.as_bytes()))
.as_bytes()
.to_vec();
let encrypted_bytes = encrypt(&password, &contents).unwrap();
let decrypted_bytes =
decrypt(&password, &encrypted_bytes).unwrap();
assert_eq!(contents, decrypted_bytes);
}
}
}
1 change: 1 addition & 0 deletions src/algo/crypto/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod aes;
pub mod ed25519;

0 comments on commit a961c2b

Please sign in to comment.