-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.rs
More file actions
241 lines (185 loc) · 7.03 KB
/
Copy pathbasic.rs
File metadata and controls
241 lines (185 loc) · 7.03 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//! Basic `rscrypto` usage across checksums, digests, MACs, KDFs, XOFs, fast hashes, AEAD,
//! hex formatting, and I/O adapters.
//!
//! Run with: `cargo run --example basic --features full,getrandom`
use std::io::{Cursor, Read, Write};
use rscrypto::{
Aead, Blake3, ChaCha20Poly1305, ChaCha20Poly1305Key, Checksum, Crc32C, Digest, Ed25519Keypair, Ed25519SecretKey,
FastHash, HkdfSha256, HmacSha256, Mac, RapidHash, Sha256, Shake256, Xof, Xxh3, aead::Nonce96,
};
fn main() -> Result<(), Box<dyn core::error::Error>> {
println!("rscrypto basic example\n");
checksum_api();
digest_api();
auth_api()?;
aead_api()?;
hex_api()?;
serialization_api();
xof_api();
fast_hash_api();
io_api()?;
Ok(())
}
/// Checksums follow `new`, `update`, `finalize`, `reset`.
fn checksum_api() {
println!("Checksums\n");
let data = b"hello world";
let oneshot = Crc32C::checksum(data);
assert_eq!(oneshot, 0xC994_65AA);
let mut streaming = Crc32C::new();
streaming.update(b"hello ");
streaming.update(b"world");
assert_eq!(streaming.finalize(), oneshot);
streaming.reset();
streaming.update(data);
assert_eq!(streaming.finalize(), oneshot);
println!("CRC-32C(\"hello world\") = 0x{oneshot:08X}\n");
}
/// Digests follow `new`, `update`, `finalize`, `reset`.
fn digest_api() {
println!("Digests\n");
let data = b"hello world";
let sha_oneshot = Sha256::digest(data);
let mut sha_stream = Sha256::new();
sha_stream.update(b"hello ");
sha_stream.update(b"world");
assert_eq!(sha_stream.finalize(), sha_oneshot);
sha_stream.reset();
sha_stream.update(data);
assert_eq!(sha_stream.finalize(), sha_oneshot);
let blake3_oneshot = Blake3::digest(data);
let mut blake3_stream = Blake3::new();
blake3_stream.update(b"hello ");
blake3_stream.update(b"world");
assert_eq!(blake3_stream.finalize(), blake3_oneshot);
blake3_stream.reset();
blake3_stream.update(data);
assert_eq!(blake3_stream.finalize(), blake3_oneshot);
println!("SHA-256 output size = {} bytes", sha_oneshot.len());
println!("BLAKE3 output size = {} bytes\n", blake3_oneshot.len());
}
/// MACs and KDFs keep the same one-shot vs stateful split.
fn auth_api() -> Result<(), Box<dyn core::error::Error>> {
println!("Auth\n");
let key = b"shared-secret";
let data = b"hello world";
let tag = HmacSha256::mac(key, data);
let mut mac = HmacSha256::new(key);
mac.update(b"hello ");
mac.update(b"world");
assert!(mac.verify(&tag).is_ok());
mac.reset();
mac.update(data);
assert!(mac.verify(&tag).is_ok());
let hkdf = HkdfSha256::new(b"salt", b"input key material");
let mut okm = [0u8; 42];
hkdf.expand(b"context", &mut okm)?;
let oneshot = HkdfSha256::derive_array::<42>(b"salt", b"input key material", b"context")?;
assert_eq!(okm, oneshot);
println!("HMAC-SHA256 tag size = {} bytes", tag.as_slice().len());
println!("HKDF-SHA256 output = {} bytes\n", okm.len());
Ok(())
}
/// AEAD: encrypt, authenticate, and decrypt with typed keys and nonces.
fn aead_api() -> Result<(), Box<dyn core::error::Error>> {
println!("AEAD\n");
let key = ChaCha20Poly1305Key::from_bytes([0x11; 32]);
let aead = ChaCha20Poly1305::new(&key);
let mut sealed = [0u8; 5 + ChaCha20Poly1305::TAG_SIZE];
let nonce = aead.seal_random(b"", b"hello", &mut sealed)?;
let mut opened = [0u8; 5];
aead.decrypt(&nonce, b"", &sealed, &mut opened)?;
assert_eq!(&opened, b"hello");
println!("ChaCha20-Poly1305 round-trip succeeded");
println!(" nonce = {nonce}\n");
Ok(())
}
/// Hex Display, FromStr, and secret key masking.
fn hex_api() -> Result<(), Box<dyn core::error::Error>> {
println!("Hex formatting\n");
let nonce = Nonce96::from_bytes([0xab; 12]);
println!("Display: {nonce}");
println!("LowerHex: {nonce:x}");
println!("UpperHex: {nonce:X}");
println!("Debug: {nonce:?}");
let parsed: Nonce96 = "abababababababababababab".parse()?;
assert_eq!(parsed, nonce);
println!("FromStr: round-trip succeeded");
let key = ChaCha20Poly1305Key::from_bytes([0x42; 32]);
let key_debug = format!("{key:?}");
assert_eq!(key_debug, "ChaCha20Poly1305Key(****)");
println!("\nSecret Debug: {key_debug}");
let ed_sk = Ed25519SecretKey::from_bytes([7u8; 32]);
let kp = Ed25519Keypair::from_secret_key(ed_sk);
println!("\nEd25519 public key: {}", kp.public_key());
let sig = kp.sign(b"hello");
println!("Ed25519 signature: {sig}");
println!();
Ok(())
}
/// Serialization via from_bytes / to_bytes / as_bytes.
fn serialization_api() {
println!("Serialization\n");
let key = ChaCha20Poly1305Key::from_bytes([0x42; 32]);
let raw: [u8; 32] = *key.as_bytes();
let restored = ChaCha20Poly1305Key::from_bytes(raw);
assert_eq!(key.as_bytes(), restored.as_bytes());
println!("Key round-trip via as_bytes/from_bytes succeeded");
let nonce = Nonce96::from_bytes([0xab; 12]);
assert_eq!(nonce, Nonce96::from_bytes(nonce.to_bytes()));
println!("Nonce round-trip succeeded\n");
}
/// XOFs support both `new`, `update`, `finalize_xof` and `xof(data)`.
fn xof_api() {
println!("XOFs\n");
let data = b"hello world";
let mut shake_stream = Shake256::xof(data);
let mut shake_stream_out = [0u8; 64];
shake_stream.squeeze(&mut shake_stream_out);
let mut shake = Shake256::new();
shake.update(data);
let mut shake_oneshot_out = [0u8; 64];
shake.finalize_xof().squeeze(&mut shake_oneshot_out);
assert_eq!(shake_stream_out, shake_oneshot_out);
let mut blake3_xof = Blake3::xof(data);
let mut blake3_out = [0u8; 64];
blake3_xof.squeeze(&mut blake3_out);
assert_eq!(&blake3_out[..32], &Blake3::digest(data));
println!("SHAKE256 produced {} bytes", shake_stream_out.len());
println!("BLAKE3 XOF produced {} bytes\n", blake3_out.len());
}
fn fast_hash_api() {
println!("Fast hashes\n");
let data = b"hello world";
let xxh_default = Xxh3::hash(data);
let xxh_seeded = Xxh3::hash_with_seed(7, data);
assert_ne!(xxh_default, xxh_seeded);
let rapid_default = RapidHash::hash(data);
let rapid_seeded = RapidHash::hash_with_seed(7, data);
assert_ne!(rapid_default, rapid_seeded);
println!("Xxh3(default) = 0x{xxh_default:016X}");
println!("RapidHash(default) = 0x{rapid_default:016X}\n");
}
fn io_api() -> std::io::Result<()> {
println!("I/O adapters\n");
let data = b"stream me through adapters";
let mut reader = Sha256::reader(Cursor::new(data.to_vec()));
let mut copied = Vec::new();
reader.read_to_end(&mut copied)?;
assert_eq!(copied, data);
assert_eq!(reader.digest(), Sha256::digest(data));
let mut checksum_writer = Crc32C::writer(Vec::new());
checksum_writer.write_all(data)?;
let (written, crc) = checksum_writer.into_parts();
assert_eq!(written, data);
assert_eq!(crc, Crc32C::checksum(data));
let mut digest_writer = Blake3::writer(Vec::new());
digest_writer.write_all(data)?;
let (written, digest) = digest_writer.into_parts();
assert_eq!(written, data);
assert_eq!(digest, Blake3::digest(data));
println!("reader digest matches Sha256::digest()");
println!("writer checksum matches Crc32C::checksum()");
println!("writer digest matches Blake3::digest()\n");
Ok(())
}