rind 0.1.2

Pure-Rust cryptography for MoQ, forked from graviola
Documentation
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Written for Graviola by Joe Birr-Pixton, 2024.
// SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT-0

//! SHA2-family hash functions.
//!
//! This is SHA256, SHA384, SHA512, and SHA512/256.
//! These are all described in [FIPS180](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).

use crate::low::cpu::verify_cpu_features;
use crate::low::{Blockwise, Zeroable, zeroise_value};

/// A context for incremental computation of SHA256.
#[derive(Clone)]
pub(crate) struct Sha256Context {
    h: [u32; 8],
    blockwise: Blockwise<{ Self::BLOCK_SZ }>,
    // u64 so 32-bit targets can hash past 4 GiB.
    nblocks: u64,
}

impl Sha256Context {
    /// Start a new SHA256 hash computation.
    pub(crate) const fn new() -> Self {
        Self {
            h: [
                0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
                0x5be0cd19,
            ],
            blockwise: Blockwise::new(),
            nblocks: 0,
        }
    }

    /// Add `bytes` to the ongoing hash computation.
    pub(crate) fn update(&mut self, bytes: &[u8]) {
        if self.blockwise.used() == 0 && bytes.len().is_multiple_of(Self::BLOCK_SZ) {
            self.update_blocks(bytes);
            return;
        }

        let bytes = self.blockwise.add_leading(bytes);

        if let Some(block) = self.blockwise.take() {
            self.update_blocks(&block);
        }

        let (whole_blocks, remainder) = {
            let whole_len = bytes.len() - (bytes.len() & (Self::BLOCK_SZ - 1));
            (&bytes[..whole_len], &bytes[whole_len..])
        };

        self.update_blocks(whole_blocks);

        self.blockwise.add_trailing(remainder);
    }

    /// Complete the SHA256 computation, returning the hash output.
    pub(crate) fn finish(mut self) -> [u8; Self::OUTPUT_SZ] {
        let bytes = self
            .nblocks
            .checked_mul(Self::BLOCK_SZ as u64)
            .and_then(|bytes| bytes.checked_add(self.blockwise.used() as u64))
            .unwrap();

        let bits = bytes
            .checked_mul(8)
            .expect("excess data processed by hash function");

        let last_blocks = self.blockwise.md_pad_with_length(&bits.to_be_bytes());
        self.update_blocks(last_blocks.as_ref());

        Self::output(&self.h)
    }

    /// The hash of the input so far followed by `tail`, leaving this context as it was.
    ///
    /// Compresses one block from a copy of the state, so the input so far
    /// must be whole blocks, and `tail` must leave room for the padding.
    pub(crate) fn finish_block(&self, tail: &[u8]) -> [u8; Self::OUTPUT_SZ] {
        assert!(self.blockwise.used() == 0 && tail.len() < Self::BLOCK_SZ - 8);
        let mut block = [0u8; Self::BLOCK_SZ];
        block[..tail.len()].copy_from_slice(tail);
        block[tail.len()] = 0x80;
        let bits = (self.nblocks * Self::BLOCK_SZ as u64 + tail.len() as u64) * 8;
        block[Self::BLOCK_SZ - 8..].copy_from_slice(&bits.to_be_bytes());

        let mut h = self.h;
        verify_cpu_features();
        crate::low::sha256_compress_blocks(&mut h, &block);

        Self::output(&h)
    }

    fn output(h: &[u32; 8]) -> [u8; Self::OUTPUT_SZ] {
        let mut r = [0u8; Self::OUTPUT_SZ];
        let (chunks, _) = r.as_chunks_mut::<4>();
        for (out, state) in chunks.iter_mut().zip(h.iter()) {
            out.copy_from_slice(&state.to_be_bytes());
        }
        r
    }
    fn update_blocks(&mut self, blocks: &[u8]) {
        debug_assert!(blocks.len().is_multiple_of(Self::BLOCK_SZ));
        if !blocks.is_empty() {
            verify_cpu_features();
            crate::low::sha256_compress_blocks(&mut self.h, blocks);
            self.nblocks = self
                .nblocks
                .saturating_add((blocks.len() / Self::BLOCK_SZ) as u64);
        }
    }

    /// The internal block size of SHA256.
    pub(crate) const BLOCK_SZ: usize = 64;

    /// The output size of SHA256.
    pub(crate) const OUTPUT_SZ: usize = 32;
}

// The state is keyed when hashing an HMAC key, and the buffer may hold secret input.
impl Drop for Sha256Context {
    fn drop(&mut self) {
        zeroise_value(self);
    }
}

impl Zeroable for Sha256Context {}

/// A context for incremental computation of SHA384.
#[derive(Clone)]
pub(crate) struct Sha384Context {
    inner: Sha512Context,
}

impl Sha384Context {
    /// Start a new SHA384 hash computation.
    pub(crate) const fn new() -> Self {
        Self {
            inner: Sha512Context::with_h([
                0xcbbb9d5dc1059ed8,
                0x629a292a367cd507,
                0x9159015a3070dd17,
                0x152fecd8f70e5939,
                0x67332667ffc00b31,
                0x8eb44a8768581511,
                0xdb0c2e0d64f98fa7,
                0x47b5481dbefa4fa4,
            ]),
        }
    }

    /// Add `bytes` to the ongoing hash computation.
    pub(crate) fn update(&mut self, bytes: &[u8]) {
        self.inner.update(bytes)
    }

    /// Complete the SHA384 computation, returning the hash output.
    pub(crate) fn finish(self) -> [u8; Self::OUTPUT_SZ] {
        let inner = self.inner.finish();
        // SAFETY: 48 is less than 64.
        inner[..Self::OUTPUT_SZ].try_into().unwrap()
    }

    /// As [`Sha512Context::finish_block`].
    pub(crate) fn finish_block(&self, tail: &[u8]) -> [u8; Self::OUTPUT_SZ] {
        let inner = self.inner.finish_block(tail);
        inner[..Self::OUTPUT_SZ].try_into().unwrap()
    }

    /// The output size of SHA384.
    pub(crate) const OUTPUT_SZ: usize = 48;
}

/// A context for incremental computation of SHA512/256.
#[derive(Clone)]
pub(crate) struct Sha512_256Context {
    inner: Sha512Context,
}

impl Sha512_256Context {
    /// Start a new SHA512/256 hash computation.
    pub(crate) const fn new() -> Self {
        Self {
            inner: Sha512Context::with_h([
                0x22312194fc2bf72c,
                0x9f555fa3c84c64c2,
                0x2393b86b6f53b151,
                0x963877195940eabd,
                0x96283ee2a88effe3,
                0xbe5e1e2553863992,
                0x2b0199fc2c85b8aa,
                0x0eb72ddc81c52ca2,
            ]),
        }
    }

    /// Add `bytes` to the ongoing hash computation.
    pub(crate) fn update(&mut self, bytes: &[u8]) {
        self.inner.update(bytes)
    }

    /// Complete the SHA512/256 computation, returning the hash output.
    pub(crate) fn finish(self) -> [u8; Self::OUTPUT_SZ] {
        let inner = self.inner.finish();
        // SAFETY: 32 is less than 64.
        inner[..Self::OUTPUT_SZ].try_into().unwrap()
    }

    /// As [`Sha512Context::finish_block`].
    pub(crate) fn finish_block(&self, tail: &[u8]) -> [u8; Self::OUTPUT_SZ] {
        let inner = self.inner.finish_block(tail);
        inner[..Self::OUTPUT_SZ].try_into().unwrap()
    }

    /// The output size of SHA512/256.
    pub(crate) const OUTPUT_SZ: usize = 32;
}

/// A context for incremental computation of SHA512.
#[derive(Clone)]
pub(crate) struct Sha512Context {
    h: [u64; 8],
    blockwise: Blockwise<{ Self::BLOCK_SZ }>,
    // u64 so 32-bit targets can hash past 4 GiB.
    nblocks: u64,
}

impl Sha512Context {
    /// Start a new SHA512 hash computation.
    pub(crate) const fn new() -> Self {
        Self::with_h([
            0x6a09e667f3bcc908,
            0xbb67ae8584caa73b,
            0x3c6ef372fe94f82b,
            0xa54ff53a5f1d36f1,
            0x510e527fade682d1,
            0x9b05688c2b3e6c1f,
            0x1f83d9abfb41bd6b,
            0x5be0cd19137e2179,
        ])
    }

    /// The truncated variants differ from SHA512 only in this initial value.
    const fn with_h(h: [u64; 8]) -> Self {
        Self {
            h,
            blockwise: Blockwise::new(),
            nblocks: 0,
        }
    }

    /// Add `bytes` to the ongoing hash computation.
    pub(crate) fn update(&mut self, bytes: &[u8]) {
        if self.blockwise.used() == 0 && bytes.len().is_multiple_of(Self::BLOCK_SZ) {
            self.update_blocks(bytes);
            return;
        }

        let bytes = self.blockwise.add_leading(bytes);

        if let Some(block) = self.blockwise.take() {
            self.update_blocks(&block);
        }

        let (whole_blocks, remainder) = {
            let whole_len = bytes.len() - (bytes.len() & (Self::BLOCK_SZ - 1));
            (&bytes[..whole_len], &bytes[whole_len..])
        };

        self.update_blocks(whole_blocks);

        self.blockwise.add_trailing(remainder);
    }

    /// Complete the SHA512 computation, returning the hash output.
    pub(crate) fn finish(mut self) -> [u8; Self::OUTPUT_SZ] {
        let bytes = self
            .nblocks
            .checked_mul(Self::BLOCK_SZ as u64)
            .and_then(|bytes| bytes.checked_add(self.blockwise.used() as u64))
            .unwrap();

        let bits = (bytes as u128)
            .checked_mul(8)
            .expect("excess data processed by hash function");

        let last_blocks = self.blockwise.md_pad_with_length(&bits.to_be_bytes());
        self.update_blocks(last_blocks.as_ref());

        Self::output(&self.h)
    }

    /// The hash of the input so far followed by `tail`, leaving this context as it was.
    ///
    /// Compresses one block from a copy of the state, so the input so far
    /// must be whole blocks, and `tail` must leave room for the padding.
    pub(crate) fn finish_block(&self, tail: &[u8]) -> [u8; Self::OUTPUT_SZ] {
        assert!(self.blockwise.used() == 0 && tail.len() < Self::BLOCK_SZ - 16);
        let mut block = [0u8; Self::BLOCK_SZ];
        block[..tail.len()].copy_from_slice(tail);
        block[tail.len()] = 0x80;
        let bits = (u128::from(self.nblocks) * Self::BLOCK_SZ as u128 + tail.len() as u128) * 8;
        block[Self::BLOCK_SZ - 16..].copy_from_slice(&bits.to_be_bytes());

        let mut h = self.h;
        verify_cpu_features();
        crate::low::sha512_compress_blocks(&mut h, &block);

        Self::output(&h)
    }

    fn output(h: &[u64; 8]) -> [u8; Self::OUTPUT_SZ] {
        let mut r = [0u8; Self::OUTPUT_SZ];
        let (chunks, _) = r.as_chunks_mut::<8>();
        for (out, state) in chunks.iter_mut().zip(h.iter()) {
            out.copy_from_slice(&state.to_be_bytes());
        }
        r
    }
    fn update_blocks(&mut self, blocks: &[u8]) {
        debug_assert!(blocks.len().is_multiple_of(Self::BLOCK_SZ));
        if !blocks.is_empty() {
            verify_cpu_features();
            crate::low::sha512_compress_blocks(&mut self.h, blocks);
            self.nblocks = self
                .nblocks
                .saturating_add((blocks.len() / Self::BLOCK_SZ) as u64);
        }
    }

    /// The internal block size of SHA512.
    pub(crate) const BLOCK_SZ: usize = 128;

    /// The output size of SHA512.
    pub(crate) const OUTPUT_SZ: usize = 64;
}

// The state is keyed when hashing an HMAC key, and the buffer may hold secret input.
impl Drop for Sha512Context {
    fn drop(&mut self) {
        zeroise_value(self);
    }
}

impl Zeroable for Sha512Context {}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn hello() {
        let mut ctx = Sha256Context::new();
        ctx.update(b"hello");
        assert_eq!(&ctx.finish(),
                   b"\x2c\xf2\x4d\xba\x5f\xb0\xa3\x0e\x26\xe8\x3b\x2a\xc5\xb9\xe2\x9e\x1b\x16\x1e\x5c\x1f\xa7\x42\x5e\x73\x04\x33\x62\x93\x8b\x98\x24");

        let mut ctx = Sha512Context::new();
        ctx.update(b"hello");
        assert_eq!(&ctx.finish(),
                   b"\x9b\x71\xd2\x24\xbd\x62\xf3\x78\x5d\x96\xd4\x6a\xd3\xea\x3d\x73\x31\x9b\xfb\xc2\x89\x0c\xaa\xda\xe2\xdf\xf7\x25\x19\x67\x3c\xa7\x23\x23\xc3\xd9\x9b\xa5\xc1\x1d\x7c\x7a\xcc\x6e\x14\xb8\xc5\xda\x0c\x46\x63\x47\x5c\x2e\x5c\x3a\xde\xf4\x6f\x73\xbc\xde\xc0\x43");
    }

    // The bit length overflows a 32-bit usize at 512 MiB, and the byte count
    // at 4 GiB.
    #[test]
    fn length_past_32_bit_usize() {
        for bytes in [1u64 << 29, 1 << 32] {
            let mut ctx = Sha256Context::new();
            ctx.nblocks = bytes / Sha256Context::BLOCK_SZ as u64;
            ctx.update(b"x");
            ctx.finish();

            let mut ctx = Sha512Context::new();
            ctx.nblocks = bytes / Sha512Context::BLOCK_SZ as u64;
            ctx.update(b"x");
            ctx.finish();
        }
    }

    #[test]
    fn sha512_long() {
        let mut data = Vec::with_capacity(1024);
        for i in 0..1024 {
            data.push(i as u8);
        }
        let mut ctx = Sha512Context::new();
        ctx.update(&data);
        assert_eq!(
            &ctx.finish(),
            &[
                55, 246, 82, 190, 134, 127, 40, 237, 3, 50, 105, 203, 186, 32, 26, 242, 17, 44, 43,
                63, 211, 52, 168, 159, 210, 247, 87, 147, 141, 222, 232, 21, 120, 124, 198, 29,
                110, 36, 168, 163, 51, 64, 208, 247, 232, 111, 252, 5, 136, 22, 184, 133, 48, 118,
                107, 166, 226, 49, 98, 10, 19, 11, 86, 108
            ]
        );
    }

    #[test]
    fn sha256_all_lengths() {
        // see cifra `vector_length` and associated
        let mut outer = Sha256Context::new();

        for len in 0..1024 {
            let mut inner = Sha256Context::new();

            for _ in 0..len {
                inner.update(&[len as u8]);
            }

            outer.update(&inner.finish());
        }

        assert_eq!(&outer.finish(),
                   b"\x55\x7b\xfd\xd5\xef\xda\xfd\x63\x06\x5e\xb7\x98\x87\xde\x86\xdb\x54\xc3\xfe\xdf\x7b\xcc\xcb\x97\x08\xfa\x87\xf0\x11\x87\x61\xdc");
    }
    #[test]
    fn sha512_all_lengths() {
        let mut outer = Sha512Context::new();

        for len in 0..1024 {
            let mut inner = Sha512Context::new();

            for _ in 0..len {
                inner.update(&[len as u8]);
            }

            outer.update(&inner.finish());
        }

        assert_eq!(&outer.finish(),
                   b"\x61\x20\x81\x2e\xd5\x0c\xc3\x11\x67\x04\x3f\x1f\x06\x9d\xcd\x4a\xd8\x83\x23\xd9\x96\x53\xd9\x67\x38\x2c\xc3\x44\x25\x69\x53\x1c\xd0\x3d\xe4\x79\x0a\x71\xde\x88\x45\x44\x66\x80\xb8\xc5\x90\xb3\x07\xc8\xae\x52\x57\x67\xf9\x28\xf8\xda\x9e\x9e\x80\xc9\x35\x5e");
    }
}