| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use crate::err::IntoResult; |
| 8 |
use crate::init; |
| 9 |
use crate::p11; |
| 10 |
use crate::p11::PK11_HashBuf; |
| 11 |
use crate::p11::SECOidTag; |
| 12 |
use crate::Error; |
| 13 |
use std::convert::TryFrom; |
| 14 |
|
| 15 |
// |
| 16 |
// Constants |
| 17 |
// |
| 18 |
|
| 19 |
pub enum HashAlgorithm { |
| 20 |
SHA2_256, |
| 21 |
SHA2_384, |
| 22 |
SHA2_512, |
| 23 |
} |
| 24 |
|
| 25 |
fn hash_alg_to_oid(alg: &HashAlgorithm) -> Result<SECOidTag::Type, Error> { |
| 26 |
match alg { |
| 27 |
HashAlgorithm::SHA2_256 => Ok(SECOidTag::SEC_OID_SHA256), |
| 28 |
HashAlgorithm::SHA2_384 => Ok(SECOidTag::SEC_OID_SHA384), |
| 29 |
HashAlgorithm::SHA2_512 => Ok(SECOidTag::SEC_OID_SHA512), |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
pub fn hash_alg_to_hash_len(alg: &HashAlgorithm) -> Result<usize, Error> { |
| 34 |
match alg { |
| 35 |
HashAlgorithm::SHA2_256 => Ok(p11::SHA256_LENGTH as usize), |
| 36 |
HashAlgorithm::SHA2_384 => Ok(p11::SHA384_LENGTH as usize), |
| 37 |
HashAlgorithm::SHA2_512 => Ok(p11::SHA512_LENGTH as usize), |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
// |
| 42 |
// Hash function |
| 43 |
// |
| 44 |
|
| 45 |
pub fn hash(alg: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, crate::Error> { |
| 46 |
init(); |
| 47 |
|
| 48 |
let data_len: i32 = match i32::try_from(data.len()) { |
| 49 |
Ok(data_len) => data_len, |
| 50 |
_ => return Err(Error::InternalError), |
| 51 |
}; |
| 52 |
let expected_len = hash_alg_to_hash_len(&alg)?; |
| 53 |
let mut digest = vec![0u8; expected_len]; |
| 54 |
unsafe { |
| 55 |
PK11_HashBuf( |
| 56 |
hash_alg_to_oid(&alg)?, |
| 57 |
digest.as_mut_ptr(), |
| 58 |
data.as_ptr(), |
| 59 |
data_len, |
| 60 |
) |
| 61 |
.into_result()? |
| 62 |
}; |
| 63 |
Ok(digest) |
| 64 |
} |