feat: add crypto.rs

This commit is contained in:
2023-02-11 17:43:37 +08:00
parent 4baf429574
commit 2eecdf8c48
4 changed files with 49 additions and 0 deletions

46
src/crypto.rs Normal file
View File

@@ -0,0 +1,46 @@
use aes_gcm::{Aes256Gcm, AesGcm, Key, KeyInit, Nonce};
use aes_gcm::aead::{AeadMut, OsRng};
use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aes::{Aes256, Aes256Enc};
use aes_gcm::aes::cipher::{Block, BlockEncrypt, BlockEncryptMut, Iv};
use aes_gcm::aes::cipher::inout::{InOut, InOutBuf};
#[test]
fn test_aes_gcm_01() {
let data_key = hex::decode("0001020304050607080910111213141516171819202122232425262728293031").unwrap();
let nonce = hex::decode("000102030405060708091011").unwrap();
let plain_text1 = "Hello world!".as_bytes();
let encrypted_text1 = "dce9511866417cff5123fa08c9e92cf156c5fc8bf6108ff28816fb58";
let plain_text2 = "This is a test message.".as_bytes();
let encrypted_text2 = hex::decode("c0e45407290878b0426fea4c09597ce323b056f975c63cce6c8da516c2a78c7d71b590c869cf92").unwrap();
let key = Key::<Aes256Gcm>::from_slice(&data_key);
let nonce = Nonce::from_slice(&nonce);
{
let mut aes256_gcm = Aes256Gcm::new(&key);
let encrypted = aes256_gcm.encrypt(&nonce, plain_text1).unwrap();
assert_eq!(encrypted_text1, hex::encode(&encrypted));
}
// {
// let mut aes256_gcm = Aes256Gcm::new(&key);
// let mut arr = [0_u8; 16];
// // let mut block = Block::<Aes256Gcm>::from(arr);
// // let mut x: [u8; 16] = [205, 129, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
// let block = GenericArray::from_mut_slice(&mut arr);
// aes256_gcm.encrypt_block_mut(&mut block);
// }
}
#[test]
fn test_aes_gcm_02() {
let data_key = hex::decode("aa01020304050607080910111213141516171819202122232425262728293031").unwrap();
let nonce = hex::decode("aa0102030405060708091011").unwrap();
let plain_text1 = "Hello world!".as_bytes();
let encrypted_text1 = hex::decode("42b625d2bacb8a514076f14002f02770e9ccd98c90e556dc267aca30").unwrap();
let plain_text2 = "This is a test message.".as_bytes();
let encrypted_text2 = hex::decode("5ebb20cdf5828e1e533ae1043ce6703cfa51574a83a069700aedefdbe2c735b01b74da214cba4a").unwrap();
}