use age::secrecy::SecretString;
use age::{Decryptor, Encryptor};
use anyhow::{Context, Result};
use std::io::{Read, Write};
pub fn encrypt(plain: &[u8], passphrase: SecretString) -> Result<Vec<u8>> {
let encryptor = Encryptor::with_user_passphrase(passphrase);
let mut ciphertext = Vec::new();
let mut writer = encryptor
.wrap_output(&mut ciphertext)
.context("failed to create age encryptor")?;
writer
.write_all(plain)
.context("failed to encrypt data")?;
writer
.finish()
.context("failed to finalize age encryption")?;
Ok(ciphertext)
}
pub fn decrypt(ciphertext: &[u8], passphrase: SecretString) -> Result<Vec<u8>> {
let decryptor = Decryptor::new(ciphertext).context("invalid age ciphertext")?;
let identity = age::scrypt::Identity::new(passphrase);
let mut reader = decryptor
.decrypt(std::iter::once(&identity as &dyn age::Identity))
.context("failed to decrypt (wrong passphrase?)")?;
let mut plaintext = Vec::new();
reader
.read_to_end(&mut plaintext)
.context("failed to read decrypted data")?;
Ok(plaintext)
}