polycrypt 0.1.1

Simple symmetric authenticated encryption in memory. Nothing fancy here.
Documentation
//! Usage:
//!
//! - Set env var `PLAINTEXT` to any plaintext string you wish to encrypt, OR
//! - Set env var `CIPHERTEXT` to any ciphertext output of this program.
//! - Set env var `KEY` to a uniformly random 32-byte key encoded in base64.
//!     e.g. `KEY=$(head -c 32 /dev/random | base64 -w0)`
//! - `cargo run` will print the encrypted/decrypted output.

use base64::Engine as _;

fn main() {
    let key_base64 = std::env::var("KEY").expect("missing KEY env var");
    let mut key = polycrypt::Key::default();
    let res = base64::engine::general_purpose::STANDARD.decode_slice(&key_base64, &mut key);
    if res != Ok(32) {
        panic!("KEY must be 32 bytes encoded as base64");
    }

    if let Ok(plaintext) = std::env::var("PLAINTEXT") {
        let ciphertext = polycrypt::encrypt(plaintext.as_ref(), &key).unwrap();
        let ciphertext_base64 = base64::engine::general_purpose::STANDARD.encode(&ciphertext);

        {
            let decrypted = polycrypt::decrypt(&ciphertext, &key).expect("decryption check failed");
            if decrypted != plaintext.as_bytes() {
                panic!("decrypted plaintext does not match input plaintext");
            }
        }

        println!("{}", ciphertext_base64);
    } else if let Ok(ciphertext_base64) = std::env::var("CIPHERTEXT") {
        let ciphertext = base64::engine::general_purpose::STANDARD
            .decode(&ciphertext_base64)
            .expect("CIPHERTEXT must be valid base64");

        let decrypted = polycrypt::decrypt(&ciphertext, &key)
            .expect("decryption failed; invalid key or auth tag");

        let decrypted_string =
            std::str::from_utf8(&decrypted).expect("decrypted plaintext is not valid UTF8");
        println!("{decrypted_string}");
    }
}