cryptouri/
hash.rs

1//! Digest types
2
3/// NIST SHA-2 family of hash functions
4mod sha2;
5
6pub use self::sha2::Sha256Hash;
7
8use crate::algorithm::SHA256_ALG_ID;
9use crate::{
10    encoding::Encodable,
11    error::{Error, ErrorKind},
12};
13use anomaly::fail;
14use std::convert::TryInto;
15
16/// Digest (i.e. hash) algorithms
17pub enum Hash {
18    /// NIST SHA-2 with a 256-bit digest
19    Sha256(Sha256Hash),
20}
21
22impl Hash {
23    /// Create a new `Digest` for the given algorithm
24    pub fn new(alg: &str, bytes: &[u8]) -> Result<Self, Error> {
25        let result = match alg {
26            SHA256_ALG_ID => Hash::Sha256(bytes.try_into()?),
27            _ => fail!(ErrorKind::AlgorithmInvalid, "{}", alg),
28        };
29
30        Ok(result)
31    }
32
33    /// Return a `Sha256Digest` if the underlying digest is SHA-256
34    pub fn sha256_digest(&self) -> Option<&Sha256Hash> {
35        match self {
36            Hash::Sha256(ref digest) => Some(digest),
37        }
38    }
39
40    /// Is this Digest a SHA-256 digest?
41    pub fn is_sha256_digest(&self) -> bool {
42        self.sha256_digest().is_some()
43    }
44}
45
46impl Encodable for Hash {
47    /// Serialize this `Digest` as a URI-encoded `String`
48    fn to_uri_string(&self) -> String {
49        match self {
50            Hash::Sha256(ref digest) => digest.to_uri_string(),
51        }
52    }
53
54    /// Serialize this `Digest` as a "dasherized" `String`
55    fn to_dasherized_string(&self) -> String {
56        match self {
57            Hash::Sha256(ref digest) => digest.to_dasherized_string(),
58        }
59    }
60}