pwsec 0.5.2

Support for password-based encryption.
Documentation
use anyhow::{Context, Result};
use pwsec::{ChachaB64, CipherB64};

fn main() -> Result<()> {
    const PBKDF2_ROUNDS: u32 = 172_234; // Choose some awkward high number

    // Usecase: you have some secret data that you want to encrypt,
    // so that you can store it to a file,
    // and later decrypt.
    let secret = b"this is some serialized form of the secret data";

    // You also have an authentication tag, which is not secret,
    // it is used to verify the integrity of the stored data.
    // It can be a hash of the data, or some other summary.
    // In this example, we use a simple string as the auth tag.
    let auth_tag = b"arbitrary, nonconfidential text";

    // You use a password to encrypt and decrypt the data, and you have to remember it
    let password = "LOIUo98zkjhB";

    // Encrypt the data and store the result
    let storage = {
        // Encrypt the secret and get the cipher text
        let cipher_b64 = ChachaB64::with_pbkdf2_rounds(PBKDF2_ROUNDS)
            .encrypt_auth(secret, auth_tag, password)?;

        (cipher_b64.to_string(), auth_tag.to_vec())
    };

    // Read the storage and decrypt the data
    {
        // Read the cipher and the auth_tag from whereever you stored them
        let (cipher, auth_tag) = storage;
        let cipher_b64 = CipherB64::parse(&cipher).context("bad decrypt")?;

        // Provide the password and decrypt the secret
        let decrypted_secret = ChachaB64::with_pbkdf2_rounds(PBKDF2_ROUNDS)
            .decrypt_auth(cipher_b64, &auth_tag, password)?;
        assert_eq!(*secret, *decrypted_secret);
    }

    Ok(())
}