Rust user input validation: Efficient error propagation
Write a Rust function that performs cryptographic operations (e.g., encryption, decryption) and handles errors.
Sample Solution:
Rust Code:
use openssl::symm::{Cipher, Crypter, Mode};
use rand::rngs::OsRng;
use rand::RngCore;
use std::error::Error;
/// Function to generate a random key for encryption
fn generate_key() -> [u8; 32] {
let mut key = [0; 32];
let mut rng = OsRng;
rng.fill_bytes(&mut key);
key
}
/// Function to encrypt data using AES encryption in ECB mode
fn encrypt_data(data: &[u8], key: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> {
let cipher = Cipher::aes_256_ecb(); // Use AES-256 ECB cipher
let mut crypter = Crypter::new(cipher, Mode::Encrypt, key, None)?;
let mut encrypted_data = vec![0; data.len() + cipher.block_size()];
let count = crypter.update(data, &mut encrypted_data)?;
let final_count = crypter.finalize(&mut encrypted_data[count..])?;
encrypted_data.truncate(count + final_count);
Ok(encrypted_data)
}
/// Function to decrypt data using AES decryption in ECB mode
fn decrypt_data(encrypted_data: &[u8], key: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> {
let cipher = Cipher::aes_256_ecb(); // Use AES-256 ECB cipher
let mut crypter = Crypter::new(cipher, Mode::Decrypt, key, None)?;
let mut decrypted_data = vec![0; encrypted_data.len() + cipher.block_size()];
let count = crypter.update(encrypted_data, &mut decrypted_data)?;
let final_count = crypter.finalize(&mut decrypted_data[count..])?;
decrypted_data.truncate(count + final_count);
Ok(decrypted_data)
}
fn main() -> Result<(), Box<dyn Error>> {
let data = b"Hello, world!";
let key = generate_key(); // Generate a random key
println!("Generated key: {:?}", key);
let encrypted_data = encrypt_data(data, &key)?;
println!("Encrypted data: {:?}", encrypted_data);
let decrypted_data = decrypt_data(&encrypted_data, &key)?;
println!("Decrypted data: {:?}", decrypted_data);
Ok(())
}
Output:
Generated key: [184, 119, 57, 95, 175, 254, 64, 238, 156, 211, 179, 54, 0, 113, 240, 89, 60, 67, 249, 15, 146, 216, 217, 116, 242, 135, 55, 84, 11, 166, 31, 235] Encrypted data: [5, 248, 93, 232, 155, 127, 43, 70, 168, 30, 255, 202, 218, 163, 124, 179] Decrypted data: [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
Explanation:
Here is a brief explanation of the above Rust code:
- Imports:
- openssl::symm::{Cipher, Crypter, Mode}: Import necessary modules from the openssl crate for cryptographic operations.
- rand::rngs::OsRng: Import the OsRng type for generating random numbers.
- rand::RngCore: Import the RngCore trait for generating random numbers.
- std::error::Error: Import the Error trait for error handling.
- Function generate_key():
- Generates a random 256-bit key for encryption using AES-256.
- Function encrypt_data():
- Encrypt the provided data using AES-256 ECB mode.
- Initializes a Crypter object with the AES-256 ECB cipher and encryption mode.
- Updates the crypter with the input data and stores the encrypted data in a vector.
- Finalizes the encryption process and truncates the encrypted data to the correct size.
- Returns the encrypted data as a vector.
- Function decrypt_data():
- Decrypt the provided encrypted data using AES-256 ECB mode.
- Initializes a Crypter object with the AES-256 ECB cipher and decryption mode.
- Updates the crypter with the encrypted data and stores the decrypted data in a vector.
- Finalizes the decryption process and truncates the decrypted data to the correct size.
- Returns the decrypted data as a vector.
- Function main():
- Generate a random key using "generate_key()".
- Encrypts the data "Hello, world!" using the generated key and prints the encrypted data.
- Decrypts the encrypted data using the same key and prints the decrypted data.
- Handle any errors during encryption, decryption, or printing.
Rust Code Editor:
Previous: Rust user input validation: Propagate Validation Errors.
Next: Rust Complex Calculation Error handling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics