8个版本
0.2.5 | 2023年3月14日 |
---|---|
0.2.4 | 2022年3月25日 |
0.2.3 | 2022年1月3日 |
0.2.1 | 2021年10月8日 |
0.1.0 | 2021年1月21日 |
#357 in 加密学
用于rinkey
330KB
5.5K SLoC
Tink-Rust: 带附加数据的流式认证加密
此crate提供与上游Tink文档中描述的相同功能的流式认证加密与附加数据。
用法
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(())
}
许可证
免责声明
这不是一个官方支持的Google产品。
依赖项
~3.5–5.5MB
~98K SLoC