Skip to content

Commit

Permalink
Add binding for single-part digest function.
Browse files Browse the repository at this point in the history
Signed-off-by: Helmut Eller <[email protected]>
  • Loading branch information
ellerh authored and ionut-arm committed Apr 22, 2023
1 parent 2ea0eb1 commit ab5b755
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
54 changes: 54 additions & 0 deletions cryptoki/src/session/digesting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Digesting functions
use crate::error::{Result, Rv};
use crate::mechanism::Mechanism;
use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

impl Session {
/// Single-part digesting operation
pub fn digest(&self, m: &Mechanism, data: &[u8]) -> Result<Vec<u8>> {
let mut mechanism: CK_MECHANISM = m.into();
let mut digest_len = 0;

unsafe {
Rv::from(get_pkcs11!(self.client(), C_DigestInit)(
self.handle(),
&mut mechanism as CK_MECHANISM_PTR,
))
.into_result()?;
}

// Get the output buffer length
unsafe {
Rv::from(get_pkcs11!(self.client(), C_Digest)(
self.handle(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
std::ptr::null_mut(),
&mut digest_len,
))
.into_result()?;
}

let mut digest = vec![0; digest_len.try_into()?];

unsafe {
Rv::from(get_pkcs11!(self.client(), C_Digest)(
self.handle(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
digest.as_mut_ptr(),
&mut digest_len,
))
.into_result()?;
}

digest.resize(digest_len.try_into()?, 0);

Ok(digest)
}
}
1 change: 1 addition & 0 deletions cryptoki/src/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use std::fmt::Formatter;
use std::marker::PhantomData;

mod decryption;
mod digesting;
mod encryption;
mod key_management;
mod object_management;
Expand Down
25 changes: 25 additions & 0 deletions cryptoki/tests/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -874,3 +874,28 @@ fn update_attributes_key() -> TestResult {

Ok(())
}

#[test]
#[serial]
fn sha256_digest() -> TestResult {
let (pkcs11, slot) = init_pins();

// open a session
let session = pkcs11.open_rw_session(slot)?;

// log in the session
session.login(UserType::User, Some(&AuthPin::new(USER_PIN.into())))?;

// data to digest
let data = vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];

let want = vec![
0x17, 0x22, 0x6b, 0x1f, 0x68, 0xae, 0xba, 0xcd, 0xef, 0x07, 0x46, 0x45, 0x0f, 0x64, 0x28,
0x74, 0x63, 0x8b, 0x29, 0x57, 0x07, 0xef, 0x73, 0xfb, 0x2c, 0x6b, 0xb7, 0xf8, 0x8e, 0x89,
0x92, 0x9f,
];
let have = session.digest(&Mechanism::Sha256, &data)?;
assert_eq!(want[..], have[..]);

Ok(())
}

0 comments on commit ab5b755

Please sign in to comment.