use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use pbkdf2::{
password_hash::{PasswordHasher, SaltString},
Pbkdf2,
};
use crate::constants::HASH_PARAMS;
use crate::encrypt::CipherData;
use crate::error::CipherError;
pub fn decrypt(password: &str, data: CipherData) -> Result<Vec<u8>, CipherError> {
let salt = SaltString::encode_b64(&data.salt)
.map_err(|e| CipherError::DecryptionError(e.to_string()))?;
let password_hash = Pbkdf2
.hash_password_customized(password.as_bytes(), None, None, HASH_PARAMS, &salt)
.map_err(|e| CipherError::DecryptionError(e.to_string()))?
.hash
.expect("content is missing after a successful hash");
let nonce = Nonce::from_slice(&data.nonce);
let cipher = Aes256Gcm::new_from_slice(password_hash.as_bytes()).expect("invalid size key");
let decrypted_bytes = cipher
.decrypt(nonce, data.encrypted_bytes.as_ref())
.map_err(|_| {
CipherError::DecryptionError("wrong password or corrupted data".to_string())
})?;
Ok(decrypted_bytes)
}