crypto_hash/imp/
cryptoapi.rs

1// Copyright (c) 2016 Mark Lee
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE.
20
21//! A cryptographic hash generator dependent upon Windows's `CryptoAPI`.
22//!
23//! Originally based on:
24//! https://github.com/rust-lang/cargo/blob/0.10.0/src/cargo/util/sha256.rs
25//! which is copyright (c) 2014 The Rust Project Developers under the MIT license.
26
27use super::Algorithm;
28use std::io;
29use std::ptr;
30use winapi::shared::minwindef::DWORD;
31use winapi::um::wincrypt::{
32    CryptAcquireContextW, CryptCreateHash, CryptDestroyHash, CryptGetHashParam, CryptHashData,
33    CryptReleaseContext, ALG_ID, CALG_MD5, CALG_SHA1, CALG_SHA_256, CALG_SHA_512, CRYPT_SILENT,
34    CRYPT_VERIFYCONTEXT, HCRYPTHASH, HCRYPTPROV, HP_HASHVAL, PROV_RSA_AES,
35};
36
37macro_rules! call {
38    ($e:expr) => {{
39        if $e == 0 {
40            panic!("failed {}: {}", stringify!($e), io::Error::last_os_error())
41        }
42    }};
43}
44
45macro_rules! finish_algorithm {
46    ($func_name: ident, $size: ident) => {
47        fn $func_name(&mut self) -> Vec<u8> {
48            let mut len = $size as u32;
49            let mut hash = [0u8; $size];
50            call!(unsafe {
51                CryptGetHashParam(self.hcrypthash, HP_HASHVAL, hash.as_mut_ptr(), &mut len, 0)
52            });
53            assert_eq!(len as usize, hash.len());
54            hash.to_vec()
55        }
56    }
57}
58
59const MD5_LENGTH: usize = 16;
60const SHA1_LENGTH: usize = 20;
61const SHA256_LENGTH: usize = 32;
62const SHA512_LENGTH: usize = 64;
63
64/// Generator of digests using a cryptographic hash function.
65///
66/// # Examples
67///
68/// ```rust
69/// use crypto_hash::{Algorithm, Hasher};
70/// use std::io::Write;
71///
72/// let mut hasher = Hasher::new(Algorithm::SHA256);
73/// hasher.write_all(b"crypto");
74/// hasher.write_all(b"-");
75/// hasher.write_all(b"hash");
76/// let result = hasher.finish();
77/// let expected =
78///     b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'"
79///     .to_vec();
80/// assert_eq!(expected, result)
81/// ```
82pub struct Hasher {
83    alg_id: ALG_ID,
84    hcryptprov: HCRYPTPROV,
85    hcrypthash: HCRYPTHASH,
86}
87
88impl Hasher {
89    /// Create a new `Hasher` for the given `Algorithm`.
90    pub fn new(algorithm: Algorithm) -> Hasher {
91        let mut hcp = 0;
92        call!(unsafe {
93            CryptAcquireContextW(
94                &mut hcp,
95                ptr::null(),
96                ptr::null(),
97                PROV_RSA_AES,
98                CRYPT_VERIFYCONTEXT | CRYPT_SILENT,
99            )
100        });
101
102        let alg_id = match algorithm {
103            Algorithm::MD5 => CALG_MD5,
104            Algorithm::SHA1 => CALG_SHA1,
105            Algorithm::SHA256 => CALG_SHA_256,
106            Algorithm::SHA512 => CALG_SHA_512,
107        };
108
109        let mut hasher = Hasher {
110            alg_id,
111            hcryptprov: hcp,
112            hcrypthash: 0,
113        };
114
115        call!(unsafe {
116            CryptCreateHash(
117                hasher.hcryptprov,
118                hasher.alg_id,
119                0,
120                0,
121                &mut hasher.hcrypthash,
122            )
123        });
124        hasher
125    }
126
127    /// Generate a digest from the data written to the `Hasher`.
128    pub fn finish(&mut self) -> Vec<u8> {
129        match self.alg_id {
130            CALG_MD5 => self.finish_md5(),
131            CALG_SHA1 => self.finish_sha1(),
132            CALG_SHA_256 => self.finish_sha256(),
133            CALG_SHA_512 => self.finish_sha512(),
134            _ => panic!("Unknown algorithm {}", self.alg_id),
135        }
136    }
137
138    finish_algorithm!(finish_md5, MD5_LENGTH);
139    finish_algorithm!(finish_sha1, SHA1_LENGTH);
140    finish_algorithm!(finish_sha256, SHA256_LENGTH);
141    finish_algorithm!(finish_sha512, SHA512_LENGTH);
142}
143
144impl io::Write for Hasher {
145    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
146        call!(unsafe {
147            CryptHashData(
148                self.hcrypthash,
149                buf.as_ptr() as *mut _,
150                buf.len() as DWORD,
151                0,
152            )
153        });
154        Ok(buf.len())
155    }
156
157    fn flush(&mut self) -> io::Result<()> {
158        Ok(())
159    }
160}
161
162impl Drop for Hasher {
163    fn drop(&mut self) {
164        if self.hcrypthash != 0 {
165            call!(unsafe { CryptDestroyHash(self.hcrypthash) });
166        }
167        call!(unsafe { CryptReleaseContext(self.hcryptprov, 0) });
168    }
169}