|
1 | 1 | //! A convenience module for hasing things with SHA-256. |
2 | 2 |
|
| 3 | +use std::{fmt, io}; |
| 4 | + |
| 5 | +use ref_cast::RefCast; |
| 6 | + |
| 7 | +use crate::hex::FromHex; |
| 8 | +use crate::{const_ref_cast, hex}; |
| 9 | + |
| 10 | +pub const HASH_LEN: usize = 32; |
| 11 | + |
| 12 | +/// A SHA-256 Hash value. |
| 13 | +#[derive(Copy, Clone, Default, PartialEq, Eq, RefCast)] |
| 14 | +#[repr(transparent)] |
| 15 | +pub struct Hash([u8; 32]); |
| 16 | + |
| 17 | +/// A SHA-256 digest accumulator. |
| 18 | +#[derive(Clone)] |
| 19 | +pub struct Context(ring::digest::Context); |
| 20 | + |
3 | 21 | /// SHA-256 digest a single input. |
4 | | -pub fn digest(input: &[u8]) -> ring::digest::Digest { |
| 22 | +pub fn digest(input: &[u8]) -> Hash { |
5 | 23 | digest_many(&[input]) |
6 | 24 | } |
7 | 25 |
|
8 | 26 | /// SHA-256 digest several input slices concatenated together, without |
9 | 27 | /// allocating. |
10 | | -pub fn digest_many(inputs: &[&[u8]]) -> ring::digest::Digest { |
11 | | - let mut ctx = context(); |
| 28 | +pub fn digest_many(inputs: &[&[u8]]) -> Hash { |
| 29 | + let mut ctx = Context::new(); |
12 | 30 | for input in inputs { |
13 | 31 | ctx.update(input); |
14 | 32 | } |
15 | 33 | ctx.finish() |
16 | 34 | } |
17 | 35 |
|
18 | | -/// Create a SHA-256 digest context for manually hashing e.g. large input files. |
19 | | -pub fn context() -> ring::digest::Context { |
20 | | - ring::digest::Context::new(&ring::digest::SHA256) |
| 36 | +/// SHA-256 digest a single input at compile time. |
| 37 | +pub const fn digest_const(input: &[u8]) -> Hash { |
| 38 | + digest_many_const(&[input]) |
| 39 | +} |
| 40 | + |
| 41 | +/// SHA-256 digest a multiple concatenated inputs at compile time. |
| 42 | +pub const fn digest_many_const(mut inputs: &[&[u8]]) -> Hash { |
| 43 | + let mut acc = sha2_const::Sha256::new(); |
| 44 | + while let Some((input, rest)) = inputs.split_first() { |
| 45 | + acc = acc.update(input); |
| 46 | + inputs = rest; |
| 47 | + } |
| 48 | + Hash::new(acc.finalize()) |
| 49 | +} |
| 50 | + |
| 51 | +// -- impl Hash -- // |
| 52 | + |
| 53 | +impl Hash { |
| 54 | + pub const fn new(value: [u8; 32]) -> Self { |
| 55 | + Self(value) |
| 56 | + } |
| 57 | + |
| 58 | + pub const fn from_ref(value: &[u8; 32]) -> &Self { |
| 59 | + const_ref_cast(value) |
| 60 | + } |
| 61 | + |
| 62 | + pub const fn as_slice(&self) -> &[u8] { |
| 63 | + self.0.as_slice() |
| 64 | + } |
| 65 | + |
| 66 | + pub const fn as_inner(&self) -> &[u8; 32] { |
| 67 | + &self.0 |
| 68 | + } |
| 69 | + |
| 70 | + pub const fn into_inner(self) -> [u8; 32] { |
| 71 | + self.0 |
| 72 | + } |
| 73 | + |
| 74 | + // Note: not pub, since `ring::digest::Digest` is not always SHA-256, but |
| 75 | + // we can guarantee this invariant inside the module. |
| 76 | + fn from_ring(output: ring::digest::Digest) -> Self { |
| 77 | + Self::new(<[u8; 32]>::try_from(output.as_ref()).unwrap()) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +impl AsRef<[u8]> for Hash { |
| 82 | + fn as_ref(&self) -> &[u8] { |
| 83 | + self.0.as_slice() |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +impl AsRef<[u8; 32]> for Hash { |
| 88 | + fn as_ref(&self) -> &[u8; 32] { |
| 89 | + &self.0 |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +impl FromHex for Hash { |
| 94 | + fn from_hex(s: &str) -> Result<Self, hex::DecodeError> { |
| 95 | + <[u8; 32]>::from_hex(s).map(Self::new) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +impl fmt::Display for Hash { |
| 100 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 101 | + write!(f, "{}", hex::display(self.as_slice())) |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +impl fmt::Debug for Hash { |
| 106 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 107 | + write!(f, "{}", self) |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +// -- impl Context -- // |
| 112 | + |
| 113 | +impl Context { |
| 114 | + pub fn new() -> Self { |
| 115 | + Self(ring::digest::Context::new(&ring::digest::SHA256)) |
| 116 | + } |
| 117 | + |
| 118 | + pub fn update(&mut self, input: &[u8]) { |
| 119 | + self.0.update(input); |
| 120 | + } |
| 121 | + |
| 122 | + pub fn finish(self) -> Hash { |
| 123 | + Hash::from_ring(self.0.finish()) |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +impl Default for Context { |
| 128 | + fn default() -> Self { |
| 129 | + Self::new() |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +impl io::Write for Context { |
| 134 | + fn write(&mut self, input: &[u8]) -> io::Result<usize> { |
| 135 | + self.update(input); |
| 136 | + Ok(input.len()) |
| 137 | + } |
| 138 | + |
| 139 | + fn flush(&mut self) -> io::Result<()> { |
| 140 | + Ok(()) |
| 141 | + } |
21 | 142 | } |
22 | 143 |
|
23 | 144 | #[cfg(test)] |
24 | 145 | mod test { |
25 | | - use super::*; |
26 | | - use crate::hex; |
| 146 | + use std::io::Write; |
| 147 | + |
| 148 | + use proptest::arbitrary::any; |
| 149 | + use proptest::proptest; |
| 150 | + |
| 151 | + use crate::{hex, sha256}; |
27 | 152 |
|
28 | 153 | // sanity check |
29 | 154 | #[test] |
30 | 155 | fn test_sha256() { |
31 | | - let actual = hex::encode(digest(b"").as_ref()); |
| 156 | + let actual = hex::encode(sha256::digest(b"").as_ref()); |
32 | 157 | let expected = |
33 | 158 | "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; |
34 | 159 | assert_eq!(&actual, expected); |
35 | 160 | } |
| 161 | + |
| 162 | + #[test] |
| 163 | + fn test_digest_equiv() { |
| 164 | + proptest!(|(inputs in any::<Vec<Vec<u8>>>())| { |
| 165 | + let inputs_ref = inputs |
| 166 | + .iter() |
| 167 | + .map(|v| v.as_slice()) |
| 168 | + .collect::<Vec<_>>(); |
| 169 | + |
| 170 | + let h1 = sha256::digest_many(&inputs_ref); |
| 171 | + let h2 = sha256::digest_many_const(&inputs_ref); |
| 172 | + |
| 173 | + let mut ctxt = sha256::Context::new(); |
| 174 | + for input in inputs_ref { |
| 175 | + ctxt.write_all(input).unwrap(); |
| 176 | + } |
| 177 | + let h3 = ctxt.finish(); |
| 178 | + |
| 179 | + assert_eq!(h1, h2); |
| 180 | + assert_eq!(h1, h3); |
| 181 | + }); |
| 182 | + } |
36 | 183 | } |
0 commit comments