secure-env 0.2.2

Encrypted environment variables manager for your shell
Documentation
use age::secrecy::SecretString;
use age::{Decryptor, Encryptor};
use anyhow::{Context, Result};
use std::io::{Read, Write};

/// Encrypt `plain` with `passphrase` using age (scrypt + ChaCha20-Poly1305).
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)
}

/// Decrypt `ciphertext` with `passphrase`, returning the plaintext bytes.
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)
}