hashlib/
sha2.rs

1// Copyright (C) 2018 Boyu Yang
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use nfhash;
10use sha2;
11
12use prelude::{HashAlgoKernel, HashError, HashOption};
13use sha2::Digest;
14
15#[derive(Debug, Default)]
16pub struct Sha2Option;
17
18impl HashOption for Sha2Option {}
19
20#[derive(Debug)]
21pub enum Sha2Error {
22    GenericError,
23}
24
25impl ::std::convert::Into<HashError> for Sha2Error {
26    fn into(self) -> HashError {
27        HashError::GenericError
28    }
29}
30
31macro_rules! impl_hash_algo_kernel_for {
32    ($struct:ident, $name:expr, $size:expr, $inner:ident, $output:ident) => {
33        pub struct $struct {
34            kernel: sha2::$inner,
35        }
36        impl HashAlgoKernel for $struct {
37            type Option = Sha2Option;
38            type Error = Sha2Error;
39            type Output = nfhash::$output;
40
41            fn name() -> &'static str {
42                $name
43            }
44
45            fn digest_size() -> usize {
46                $size
47            }
48
49            fn new(_opt: Sha2Option) -> Self {
50                let kernel = sha2::$inner::new();
51                Self { kernel }
52            }
53
54            fn update<T>(&mut self, data: T) -> Result<(), Self::Error>
55            where
56                T: ::std::convert::AsRef<[u8]>,
57            {
58                self.kernel.input(data);
59                Ok(())
60            }
61
62            fn finalize(self) -> Result<Self::Output, Self::Error> {
63                let digest = self.kernel.result();
64                Self::Output::from_slice(digest.as_slice()).map_err(|_| Sha2Error::GenericError)
65            }
66        }
67    };
68}
69
70impl_hash_algo_kernel_for!(Sha224, "sha-224", 224, Sha224, H224);
71impl_hash_algo_kernel_for!(Sha256, "sha-256", 256, Sha256, H256);
72impl_hash_algo_kernel_for!(Sha384, "sha-384", 384, Sha384, H384);
73impl_hash_algo_kernel_for!(Sha512, "sha-512", 512, Sha512, H512);
74impl_hash_algo_kernel_for!(Sha512_224, "sha-512/224", 224, Sha512Trunc224, H224);
75impl_hash_algo_kernel_for!(Sha512_256, "sha-512/256", 256, Sha512Trunc256, H256);