Skip to main content

arcana/hash/
sha384.rs

1//! SHA-384 hash function (FIPS 180-4).
2//!
3//! Same as SHA-512 but with different initial values, truncated to 384 bits (48 bytes).
4
5use super::sha512::Sha512;
6use crate::Hasher;
7
8const H0_384: [u64; 8] = [
9    0xcbbb9d5dc1059ed8,
10    0x629a292a367cd507,
11    0x9159015a3070dd17,
12    0x152fecd8f70e5939,
13    0x67332667ffc00b31,
14    0x8eb44a8768581511,
15    0xdb0c2e0d64f98fa7,
16    0x47b5481dbefa4fa4,
17];
18
19/// SHA-384 hasher (FIPS 180-4). 384-bit output, 128-byte blocks.
20///
21/// SHA-384 reuses the SHA-512 internal compression function with
22/// different IV constants and a truncated output. Used by TLS 1.3
23/// for the higher security tier (paired with P-384) and by FIPS
24/// 186-5 for the canonical P-384 ECDSA hash.
25#[derive(Clone)]
26pub struct Sha384 {
27    inner: Sha512,
28}
29
30impl Hasher for Sha384 {
31    const OUTPUT_LEN: usize = 48;
32    const BLOCK_LEN: usize = 128;
33
34    fn new() -> Self {
35        Self {
36            inner: Sha512::new_with_iv(H0_384),
37        }
38    }
39
40    fn update(&mut self, data: &[u8]) {
41        self.inner.update(data);
42    }
43
44    fn finalize(self) -> Vec<u8> {
45        let mut out = vec![0u8; 48];
46        self.finalize_into(&mut out);
47        out
48    }
49
50    fn finalize_into(self, out: &mut [u8]) {
51        let mut full = [0u8; 64];
52        self.inner.finalize_into(&mut full);
53        let len = out.len().min(48);
54        out[..len].copy_from_slice(&full[..len]);
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use crate::Hasher;
62
63    #[test]
64    fn test_sha384_empty() {
65        let digest = Sha384::hash(b"");
66        let expected: [u8; 48] = [
67            0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, 0x21, 0xfd,
68            0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, 0x27, 0x4e, 0xde, 0xbf,
69            0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b,
70        ];
71        assert_eq!(&digest[..], &expected[..]);
72    }
73
74    #[test]
75    fn test_sha384_abc() {
76        let digest = Sha384::hash(b"abc");
77        let expected: [u8; 48] = [
78            0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b, 0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07, 0x27, 0x2c,
79            0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63, 0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed, 0x80, 0x86, 0x07, 0x2b,
80            0xa1, 0xe7, 0xcc, 0x23, 0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7,
81        ];
82        assert_eq!(&digest[..], &expected[..]);
83    }
84}