Created
January 10, 2025 09:53
-
-
Save yogithesymbian/a14ceee5439a471d53cd07d24627f4bb to your computer and use it in GitHub Desktop.
aes-256-cbc rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use aes::Aes256; | |
use block_modes::{BlockMode, Cbc}; | |
use block_modes::block_padding::Pkcs7; | |
use hex::{decode, encode}; | |
use std::str; | |
// Define the type for AES-256-CBC | |
type Aes256Cbc = Cbc<Aes256, Pkcs7>; | |
fn main() { | |
// Example key and IV (both should be 32 and 16 bytes, respectively) | |
let key = b"01234567890123456789012345678901"; // 32-byte key | |
let iv = b"abcdef1234567890"; // 16-byte initialization vector | |
// Encrypted message in hex format | |
let encrypted_hex = "76a6c3b47ff237f4d1a735b078e2f89e"; | |
// Convert the hex string to bytes | |
let encrypted_bytes = decode(encrypted_hex).expect("Failed to decode hex"); | |
// Decrypt the message | |
let decrypted_data = decrypt_aes_256_cbc(&key[..], &iv[..], &encrypted_bytes); | |
// Print the decrypted message | |
match decrypted_data { | |
Ok(message) => println!("Decrypted message: {}", message), | |
Err(e) => eprintln!("Decryption failed: {}", e), | |
} | |
} | |
fn decrypt_aes_256_cbc(key: &[u8], iv: &[u8], encrypted_data: &[u8]) -> Result<String, String> { | |
// Create a cipher instance | |
let cipher = Aes256Cbc::new_from_slices(key, iv) | |
.map_err(|e| format!("Invalid key/IV: {}", e))?; | |
// Perform decryption | |
let decrypted_data = cipher | |
.decrypt_vec(encrypted_data) | |
.map_err(|e| format!("Decryption error: {}", e))?; | |
// Convert decrypted data to a UTF-8 string | |
String::from_utf8(decrypted_data).map_err(|e| format!("Invalid UTF-8: {}", e)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment