Coverage Report

Created: 2026-05-18 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/git/checkouts/nss-rs-71e20fe79ef91440/9b94ca3/src/hash.rs
Line
Count
Source
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 std::convert::TryFrom as _;
8
9
use crate::{
10
    Error,
11
    err::IntoResult as _,
12
    init, p11,
13
    p11::{PK11_HashBuf, SECOidTag},
14
};
15
16
//
17
// Constants
18
//
19
20
pub enum HashAlgorithm {
21
    SHA2_256,
22
    SHA2_384,
23
    SHA2_512,
24
}
25
26
0
const fn hash_alg_to_oid(alg: &HashAlgorithm) -> SECOidTag::Type {
27
0
    match alg {
28
0
        HashAlgorithm::SHA2_256 => SECOidTag::SEC_OID_SHA256,
29
0
        HashAlgorithm::SHA2_384 => SECOidTag::SEC_OID_SHA384,
30
0
        HashAlgorithm::SHA2_512 => SECOidTag::SEC_OID_SHA512,
31
    }
32
0
}
33
34
#[must_use]
35
0
pub const fn hash_alg_to_hash_len(alg: &HashAlgorithm) -> usize {
36
0
    match alg {
37
0
        HashAlgorithm::SHA2_256 => p11::SHA256_LENGTH as usize,
38
0
        HashAlgorithm::SHA2_384 => p11::SHA384_LENGTH as usize,
39
0
        HashAlgorithm::SHA2_512 => p11::SHA512_LENGTH as usize,
40
    }
41
0
}
42
43
//
44
// Hash function
45
//
46
47
0
pub fn hash(alg: &HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, Error> {
48
0
    init()?;
49
50
0
    let data_len: i32 = match i32::try_from(data.len()) {
51
0
        Ok(data_len) => data_len,
52
0
        _ => return Err(Error::Internal),
53
    };
54
0
    let expected_len = hash_alg_to_hash_len(alg);
55
0
    let mut digest = vec![0u8; expected_len];
56
    unsafe {
57
0
        PK11_HashBuf(
58
0
            hash_alg_to_oid(alg),
59
0
            digest.as_mut_ptr(),
60
0
            data.as_ptr(),
61
0
            data_len,
62
        )
63
0
        .into_result()?;
64
    };
65
0
    Ok(digest)
66
0
}