crypto_lib 0.1.0

A cryptographic library providing SHA-256 hashing, AES-128-CBC encryption and decryption, and utilities for generating random keys and IVs.
Documentation
use sha2::{Sha256, Digest};
use aes::Aes128;
use block_modes::{BlockMode, Cbc};
use block_modes::block_padding::Pkcs7;
use rand::Rng;
use hex::{encode, decode};

type Aes128Cbc = Cbc<Aes128, Pkcs7>;


pub fn sha256_hash(input: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(input);
    encode(hasher.finalize())
}

pub fn encrypt_aes(key: &[u8; 16], iv: &[u8; 16], plaintext: &str) -> String {
    let cipher = Aes128Cbc::new_from_slices(key, iv).unwrap();
    let ciphertext = cipher.encrypt_vec(plaintext.as_bytes());
    encode(ciphertext)
}


pub fn decrypt_aes(key: &[u8; 16], iv: &[u8; 16], ciphertext: &str) -> String {
    let cipher = Aes128Cbc::new_from_slices(key, iv).unwrap();
    let decrypted_bytes = cipher.decrypt_vec(&decode(ciphertext).unwrap()).unwrap();
    String::from_utf8(decrypted_bytes).unwrap()
}


pub fn generate_key() -> [u8; 16] {
    let mut key = [0u8; 16];
    rand::thread_rng().fill(&mut key);
    key
}


pub fn generate_iv() -> [u8; 16] {
    let mut iv = [0u8; 16];
    rand::thread_rng().fill(&mut iv);
    iv
}