8 releases
0.2.5 | Mar 14, 2023 |
---|---|
0.2.4 | Mar 25, 2022 |
0.2.3 | Jan 3, 2022 |
0.2.1 | Oct 8, 2021 |
0.1.0 | Jan 21, 2021 |
#788 in Cryptography
40 downloads per month
Used in rinkey
330KB
5.5K
SLoC
Tink-Rust: Streaming Authenticated Encryption with Additional Data
This crate provides streaming authenticated encryption with additional data functionality, as described in the upstream Tink documentation.
Usage
fn main() -> Result<(), Box<dyn Error>> {
let dir = tempfile::tempdir()?.into_path();
let ct_filename = dir.join("ciphertext.bin");
tink_streaming_aead::init();
// Generate fresh key material.
let kh =
tink_core::keyset::Handle::new(&tink_streaming_aead::aes128_gcm_hkdf_4kb_key_template())?;
// Get the primitive that uses the key material.
let a = tink_streaming_aead::new(&kh)?;
// Use the primitive to create a [`std::io::Write`] object that writes ciphertext
// to a file.
let aad = b"this data needs to be authenticated, but not encrypted";
let ct_file = std::fs::File::create(ct_filename.clone())?;
let mut w = a.new_encrypting_writer(Box::new(ct_file), &aad[..])?;
// Write data to the encrypting-writer, in chunks to simulate streaming.
let mut offset = 0;
while offset < PT.len() {
let end = std::cmp::min(PT.len(), offset + CHUNK_SIZE);
let written = w.write(&PT[offset..end])?;
offset += written;
// Can flush but it does nothing.
w.flush()?;
}
// Complete the encryption (process any remaining buffered plaintext).
w.close()?;
// For the other direction, given a [`std::io::Read`] object that reads ciphertext,
// use the primitive to create a [`std::io::Read`] object that emits the corresponding
// plaintext.
let ct_file = std::fs::File::open(ct_filename)?;
let mut r = a.new_decrypting_reader(Box::new(ct_file), &aad[..])?;
// Read data from the decrypting-reader, in chunks to simulate streaming.
let mut recovered = vec![];
loop {
let mut chunk = vec![0; CHUNK_SIZE];
let len = r.read(&mut chunk)?;
if len == 0 {
break;
}
recovered.extend_from_slice(&chunk[..len]);
}
assert_eq!(recovered, PT);
Ok(())
}
License
Disclaimer
This is not an officially supported Google product.
Dependencies
~3.5–5.5MB
~101K SLoC