< 返回版块

fengyexin9 发表于 2021-06-30 16:48

java使用 AES加密,模式CBC,填充PKCS5Padding,数据128位,偏移量16位

需要rust中对应的加密和解密的文档。

Java中传入的key(String)和iv(String)对应 rust中key([u8,32]),iv([u8,16])

rust中如何将字符串转换为[u8,32] 和[u8,16]?

评论区

写评论
tokyohuang123 2021-08-18 18:30

老哥 我用了你发的 怎么老是说不合法呢 let text=String::from("12312312"); let keytext=String::from("12345678123456781234567812345678"); let iv=String::from("1234567812345678"); let dtext =encrypt(text,keytext,iv); println!("{:?}",dtext); 32位key和16位iv哪里错了 thread 'main' panicked at 'called Result::unwrap() on an Err value: InvalidKeyIvLength', src/untils/aes.rs:14:56

作者 fengyexin9 2021-07-08 17:45

#加密 rust-crypto = "0.2.36" aes = "0.7.4" block-modes = "0.8.1" hex-literal = "0.2.1"

json = "0.12.4" ferris-says = "0.2" base64 = "0.12.1"

use aes::Aes128; use block_modes::block_padding::Pkcs7;

use block_modes::{BlockMode, Cbc}; use base64::{encode, decode};

/** 加密 **/ pub fn encrypt(data: String,keystr: String,ivstr: String) -> String{ type Aes128Cbc = Cbc<Aes128, Pkcs7>; let key =&keystr.as_bytes(); let iv = &ivstr.as_bytes(); let plaintext = data.as_bytes(); let cipher = Aes128Cbc::new_from_slices(&key, &iv).unwrap(); let mut buffer = [0u8; 32]; // copy message to the buffer let pos = plaintext.len(); buffer[..pos].copy_from_slice(plaintext); let ciphertext = cipher.encrypt(&mut buffer, pos).unwrap(); let enc=encode(ciphertext); enc }

/** 解密 **/ pub fn decrypt(data: String,keystr: String,ivstr: String) -> String { type Aes128Cbc = Cbc<Aes128, Pkcs7>; let key =&keystr.as_bytes(); let iv = &ivstr.as_bytes();

let cipher = Aes128Cbc::new_from_slices(&key, &iv).unwrap();
let mut buf = decode(data).unwrap();
let decrypted_ciphertext = cipher.decrypt(&mut buf).unwrap();

let res=std::str::from_utf8(decrypted_ciphertext).unwrap();
res.to_string()

}

Paulswith 2021-07-06 17:21

碰巧跟你有过同样的需求,这是我之前弄的,希望能帮到你。

let key = kv_pair[0].trim().as_bytes();
let iv = kv_pair[1].trim().as_bytes();
let cipher_4_dec = Aes128Cbc::new_var(key, iv).expect("Initial cipher fail");
chenge 2021-06-30 17:23

好像有个.bytes()

1 共 4 条评论, 1 页