Encryption and Decryption AES-GCM 256

i was trying to do a encryption and decryption in rust using aes-gcm , so here is the encryption code

pub fn encrypt(data: &[u8], password: &str) {
let password_byte = password.as_bytes();

let key: &Key<Aes256Gcm> = password_byte.into();
let cipher = Aes256Gcm::new(&key);
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
println!("{:?}", nonce);

let encrypted_data = match cipher.encrypt(&nonce, data) {
    Ok(encrpted) => {

        encrpted
    }
    Err(err) => {
        vec![0u8; 32]
    }
};

so far encryption is working properly , it is the decryption part im trying to understand , theoretically decryption consist of three parts
1)IV
2)Salt
3) encrypted data
how to split them and ecrypt the data in rust

AES-GCM derives the IV from the nonce I believe. The nonce and the ciphertext are stored separately with the aes-gcm crate. You just need to store both parts and pass them back in when decrypting.

here is the working code

pub fn encrypt(data: &[u8], password: &str) {
let password_byte = password.as_bytes();

let key: &Key<Aes256Gcm> = password_byte.into();
let cipher = Aes256Gcm::new(&key);
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);


let encrypted_data = match cipher.encrypt(&nonce,data)
{
    Ok(encrpted) => {

        let e = block { data: encrpted, nonce:nonce.to_vec() };
        e
    }
    Err(err) => {
        panic!("could not encrypt")
    }
};

pub fn decrypt( encryptedTex: &block, password:&str) {
let password_byte = password.as_bytes();
let key: &Key = password_byte.into();
let nonce = &encryptedTex.nonce;
let data = &encryptedTex.data;

let nonce = aes_gcm::Nonce::from_slice(&nonce);

let cipher = Aes256Gcm::new(&key);
let op = cipher.decrypt(&nonce ,data.as_slice());
//  let plaintext = cipher.decrypt(nonce, &*encryptedTex[15..].as_ref()).unwrap();

}

pub struct block {
data: Vec,
nonce: Vec
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.