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
use crate::error::*;
pub use nss::pk11::context::HashAlgorithm::{self as Algorithm, *};
#[derive(Clone)]
pub struct Digest {
pub(crate) value: Vec<u8>,
pub(crate) algorithm: Algorithm,
}
impl Digest {
pub fn algorithm(&self) -> &Algorithm {
&self.algorithm
}
}
impl AsRef<[u8]> for Digest {
fn as_ref(&self) -> &[u8] {
self.value.as_ref()
}
}
pub fn digest(algorithm: &Algorithm, data: &[u8]) -> Result<Digest> {
let value = nss::pk11::context::hash_buf(algorithm, data)?;
Ok(Digest {
value,
algorithm: *algorithm,
})
}
#[cfg(test)]
mod tests {
use super::*;
const MESSAGE: &[u8] = b"bobo";
const DIGEST_HEX: &str = "bf0c97708b849de696e7373508b13c5ea92bafa972fc941d694443e494a4b84d";
#[test]
fn sha256_digest() {
assert_eq!(hex::encode(&digest(&SHA256, MESSAGE).unwrap()), DIGEST_HEX);
assert_ne!(
hex::encode(&digest(&SHA256, b"notbobo").unwrap()),
DIGEST_HEX
);
}
#[test]
fn digest_cleanly_rejects_gigantic_messages() {
let message = vec![0; (std::i32::MAX as usize) + 1];
assert!(digest(&SHA256, &message).is_err());
}
}