Skip to content

Implement PKCS#11 3.0 MessageSign API #270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cryptoki/src/mechanism/eddsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ impl EddsaParams<'_> {
///
/// # Arguments
///
/// * `params` - The CK_EDDSA_PARAMS structure.
/// * `scheme` - The EdDSA signature scheme.
///
/// # Returns
///
Expand Down
18 changes: 17 additions & 1 deletion cryptoki/src/mechanism/mechanism_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ bitflags! {
const EC_COMPRESS = CKF_EC_COMPRESS;
const MESSAGE_ENCRYPT = CKF_MESSAGE_ENCRYPT;
const MESSAGE_DECRYPT = CKF_MESSAGE_DECRYPT;
const MESSAGE_SIGN = CKF_MESSAGE_SIGN;
const MESSAGE_VERIFY = CKF_MESSAGE_VERIFY;
const MULTI_MESSAGE = CKF_MULTI_MESSAGE;
}
}
Expand Down Expand Up @@ -246,6 +248,20 @@ impl MechanismInfo {
self.flags.contains(MechanismInfoFlags::MESSAGE_DECRYPT)
}

/// True if the mechanism can be used to sign messages
///
/// See [`Session::sign_message`](crate::session::Session::sign_message)
pub fn message_sign(&self) -> bool {
self.flags.contains(MechanismInfoFlags::MESSAGE_SIGN)
}

/// True if the mechanism can be used to verify signed messages
///
/// See [`Session::decrypt`](crate::session::Session::verify_message)
pub fn message_verify(&self) -> bool {
self.flags.contains(MechanismInfoFlags::MESSAGE_VERIFY)
}

/// True if the mechanism can be used with encrypt/decrypt_message_begin API.
/// One of message_* flag must also be set.
///
Expand Down Expand Up @@ -294,7 +310,7 @@ HW | ENCRYPT | DECRYPT | DIGEST | SIGN | SIGN_RECOVER | VERIFY | \
VERIFY_RECOVER | GENERATE | GENERATE_KEY_PAIR | WRAP | UNWRAP | DERIVE | \
EXTENSION | EC_F_P | EC_F_2M | EC_ECPARAMETERS | EC_NAMEDCURVE | \
EC_OID | EC_UNCOMPRESS | EC_COMPRESS | MESSAGE_ENCRYPT | MESSAGE_DECRYPT | \
MULTI_MESSAGE";
MESSAGE_SIGN | MESSAGE_VERIFY | MULTI_MESSAGE";
let all = MechanismInfoFlags::all();
let observed = format!("{all:#?}");
println!("{observed}");
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/message_decryption.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright 2025 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Encrypting data
//! Decrypting messages
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵️

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, did not write it right the first time :)


use crate::context::Function;
use crate::error::{Result, Rv};
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/message_encryption.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright 2025 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Encrypting data
//! Encrypting messages

use crate::context::Function;
use crate::error::{Result, Rv};
Expand Down
246 changes: 246 additions & 0 deletions cryptoki/src/session/message_signing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
// Copyright 2025 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Message Signing/Verification and authentication functions

use crate::context::Function;
use crate::error::{Result, Rv};
use crate::mechanism::{Mechanism, MessageParam};
use crate::object::ObjectHandle;
use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

impl Session {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we re-organize the methods here to split single-part and multi-part?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was starting from the sign/verify API, which was in a single file. The semantics is also interleaved as we need to initialize the operation first and then call either one-shot or multipart operations, which really does not make a good split as for both of the ways, we need the operation initialization.

/// Prepare a session for one or more Message-based signature using the same mechanism and key
pub fn message_sign_init(&self, mechanism: &Mechanism, key: ObjectHandle) -> Result<()> {
let mut mechanism: CK_MECHANISM = mechanism.into();

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

Ok(())
}

/// Sign a message in single part
pub fn sign_message(&self, param: &MessageParam, data: &[u8]) -> Result<Vec<u8>> {
let mut signature_len = 0;

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

let mut signature = vec![0; signature_len.try_into()?];

unsafe {
Rv::from(get_pkcs11!(self.client(), C_SignMessage)(
self.handle(),
param.as_ptr(),
param.len(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
signature.as_mut_ptr(),
&mut signature_len,
))
.into_result(Function::SignMessage)?;
}

signature.resize(signature_len.try_into()?, 0);

Ok(signature)
}

/// Begin multi-part message signature operation
pub fn sign_message_begin(&self, param: MessageParam) -> Result<()> {
unsafe {
Rv::from(get_pkcs11!(self.client(), C_SignMessageBegin)(
self.handle(),
param.as_ptr(),
param.len(),
))
.into_result(Function::SignMessageBegin)
}
}

/// Continue mutli-part message signature operation
pub fn sign_message_next(
&self,
param: MessageParam,
data: &[u8],
end: bool,
) -> Result<Option<Vec<u8>>> {
if !end {
// Just pass in the data
unsafe {
Rv::from(get_pkcs11!(self.client(), C_SignMessageNext)(
self.handle(),
param.as_ptr(),
param.len(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
std::ptr::null_mut(),
std::ptr::null_mut(),
))
.into_result(Function::SignMessageNext)?;
}
return Ok(None);
}
let mut signature_len = 0;
unsafe {
Rv::from(get_pkcs11!(self.client(), C_SignMessageNext)(
self.handle(),
param.as_ptr(),
param.len(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
std::ptr::null_mut(),
&mut signature_len,
))
.into_result(Function::SignMessageNext)?;
}

let mut signature = vec![0; signature_len.try_into()?];

unsafe {
Rv::from(get_pkcs11!(self.client(), C_SignMessageNext)(
self.handle(),
param.as_ptr(),
param.len(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
signature.as_mut_ptr(),
&mut signature_len,
))
.into_result(Function::SignMessageNext)?;
}

signature.resize(signature_len.try_into()?, 0);

Ok(Some(signature))
}

/// Finalize mutli-part message signature process
pub fn message_sign_final(&self) -> Result<()> {
unsafe {
Rv::from(get_pkcs11!(self.client(), C_MessageSignFinal)(
self.handle(),
))
.into_result(Function::MessageSignFinal)
}
}

/// Prepare a session for one or more Message-based verifications using the same mechanism and key
pub fn message_verify_init(&self, mechanism: &Mechanism, key: ObjectHandle) -> Result<()> {
let mut mechanism: CK_MECHANISM = mechanism.into();

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

Ok(())
}

/// Verify message in single-part
pub fn verify_message(
&self,
param: &MessageParam,
data: &[u8],
signature: &[u8],
) -> Result<()> {
unsafe {
Rv::from(get_pkcs11!(self.client(), C_VerifyMessage)(
self.handle(),
param.as_ptr(),
param.len(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
signature.as_ptr() as *mut u8,
signature.len().try_into()?,
))
.into_result(Function::VerifyMessage)?;
}
Ok(())
}

/// Begin multi-part message signature verification operation
pub fn verify_message_begin(&self, param: MessageParam) -> Result<()> {
unsafe {
Rv::from(get_pkcs11!(self.client(), C_VerifyMessageBegin)(
self.handle(),
param.as_ptr(),
param.len(),
))
.into_result(Function::VerifyMessageBegin)
}
}

/// Continue mutli-part message signature verification operation
pub fn verify_message_next(
&self,
param: MessageParam,
data: &[u8],
signature: Option<&[u8]>,
) -> Result<()> {
match signature {
None => {
// Just pass in the data
unsafe {
Rv::from(get_pkcs11!(self.client(), C_VerifyMessageNext)(
self.handle(),
param.as_ptr(),
param.len(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
std::ptr::null_mut(),
0,
))
.into_result(Function::VerifyMessageNext)?;
}
return Ok(());
}
Some(s) => unsafe {
Rv::from(get_pkcs11!(self.client(), C_VerifyMessageNext)(
self.handle(),
param.as_ptr(),
param.len(),
data.as_ptr() as *mut u8,
data.len().try_into()?,
s.as_ptr() as *mut u8,
s.len().try_into()?,
))
.into_result(Function::VerifyMessageNext)?;
},
}
Ok(())
}

/// Finalize mutli-part message signature verification process
pub fn message_verify_final(&self) -> Result<()> {
unsafe {
Rv::from(get_pkcs11!(self.client(), C_MessageVerifyFinal)(
self.handle(),
))
.into_result(Function::MessageVerifyFinal)
}
}
}
1 change: 1 addition & 0 deletions cryptoki/src/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod encryption;
mod key_management;
mod message_decryption;
mod message_encryption;
mod message_signing;
mod object_management;
mod random;
mod session_info;
Expand Down
Loading