1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const CHUNK_SIZE: usize = 20;
const PT: &[u8] = b"This is a long string that will be written in chunks to the encrypting writer. It needs to be longer than several of the CHUNK_SIZE chunks, so that there are multiple write operations demonstrated";
fn main() {
let dir = tempfile::tempdir().unwrap().into_path();
let ct_filename = dir.join("ciphertext.bin");
tink_streaming_aead::init();
let kh =
tink_core::keyset::Handle::new(&tink_streaming_aead::aes128_gcm_hkdf_4kb_key_template())
.unwrap();
let a = tink_streaming_aead::new(&kh).unwrap();
let aad = b"this data needs to be authenticated, but not encrypted";
let ct_file = std::fs::File::create(ct_filename.clone()).unwrap();
let mut w = a
.new_encrypting_writer(Box::new(ct_file), &aad[..])
.unwrap();
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]).unwrap();
offset += written;
w.flush().unwrap();
}
w.close().unwrap();
let ct_file = std::fs::File::open(ct_filename).unwrap();
let mut r = a
.new_decrypting_reader(Box::new(ct_file), &aad[..])
.unwrap();
let mut recovered = vec![];
loop {
let mut chunk = vec![0; CHUNK_SIZE];
let len = r.read(&mut chunk).unwrap();
if len == 0 {
break;
}
recovered.extend_from_slice(&chunk[..len]);
}
assert_eq!(recovered, PT);
}