rust implementation
This commit is contained in:
54
src/crypto.rs
Normal file
54
src/crypto.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
use std::fmt;
|
||||
|
||||
use aes::Aes128;
|
||||
use base64::{engine::general_purpose::STANDARD, Engine as _};
|
||||
use cbc::{
|
||||
cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit},
|
||||
Decryptor,
|
||||
};
|
||||
|
||||
type Aes128CbcDec = Decryptor<Aes128>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CryptoError {
|
||||
Base64(base64::DecodeError),
|
||||
Aes(cbc::cipher::InvalidLength),
|
||||
Unpad(cbc::cipher::block_padding::UnpadError),
|
||||
}
|
||||
|
||||
impl fmt::Display for CryptoError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
CryptoError::Base64(e) => write!(f, "Base64 decode failed: {}", e),
|
||||
CryptoError::Aes(e) => write!(f, "AES decryption failed: {}", e),
|
||||
CryptoError::Unpad(e) => write!(f, "PKCS7 unpadding failed: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CryptoError {}
|
||||
|
||||
pub fn decrypt(ciphertext_b64: &str, key: &str, iv: &str) -> Result<String, CryptoError> {
|
||||
// 1. Base64 decode the ciphertext
|
||||
let ciphertext = STANDARD
|
||||
.decode(ciphertext_b64)
|
||||
.map_err(CryptoError::Base64)?;
|
||||
|
||||
// 2. Initialize AES-128 in CBC mode
|
||||
let key_bytes = key.as_bytes();
|
||||
let iv_bytes = iv.as_bytes();
|
||||
let decryptor = Aes128CbcDec::new_from_slices(key_bytes, iv_bytes).map_err(CryptoError::Aes)?;
|
||||
|
||||
// 3. Decrypt the ciphertext, handling padding
|
||||
let decrypted_len = ciphertext.len();
|
||||
let mut plaintext = vec![0u8; decrypted_len];
|
||||
let copy_len = ciphertext.len();
|
||||
plaintext[..copy_len].copy_from_slice(&ciphertext);
|
||||
|
||||
let plaintext_slice = decryptor
|
||||
.decrypt_padded_mut::<Pkcs7>(&mut plaintext[..decrypted_len])
|
||||
.map_err(CryptoError::Unpad)?;
|
||||
|
||||
// 4. Convert plaintext to a UTF-8 string
|
||||
Ok(String::from_utf8_lossy(plaintext_slice).to_string())
|
||||
}
|
||||
Reference in New Issue
Block a user