Skip to content

Requesting an example #576

Description

@David-OConnor

Hi! Does anyone have an example of basic operation, that includes a function or struct field containing each relevant type (key, poly, nonce)? Thank you!

Here is my non-compiling attempt:

Cargo.toml:

crypto = { package = "chacha20poly1305", version = "^0.10.1", default-features = false, features = ["rand_core"] }
rand_core = "^0.6.4"
generic-array = "^1.0.0"

Program:

use chacha20poly1305::{
    aead::{AeadCore, KeyInit},
    ChaCha20Poly1305 as Poly, Nonce
};
use generic_array::GenericArray;

type Key = GenericArray<u8, 12>;
type Nonce2 = GenericArray<u8, 12>;

pub fn make_cipher(rng: &mut Rng) -> (Key, Poly, Nonce) {
    let key = Poly::generate_key(rng);
    let cipher = Poly::new(&key);

    // The nonce is unique per message. 96-bits.
    let nonce = Poly::generate_nonce(rng);

    (key, cipher, nonce)
}

pub fn encrypt(data: &mut [u8], cipher: &Poly, nonce: &Nonce) {
    let ciphertext = cipher.encrypt(&nonce, data).unwrap();
}

pub fn decrypt(data: &mut [u8], cipher: &Poly, nonce: &Nonce) {
    let ciphertext = cipher.decrypt(&nonce, data).unwrap();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions