Skip to content

Commit

Permalink
feat(session): support Signer trait through a Session
Browse files Browse the repository at this point in the history
`signature` is a widely used "standard" trait offering high level APIs to manipulate
signers and verifiers.

This implements a `Signer` trait on a returned `SignatureRequest` through `Session` which is
a prepared "signature request" with filled mechanism and key.

This makes it possible to wire cryptoki further with other APIs of the Rust ecosystem.
  • Loading branch information
RaitoBezarius committed Jul 8, 2023
1 parent e0ec792 commit 507f574
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions cryptoki/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ psa-crypto = { version = "0.9.0", default-features = false, optional = true }
cryptoki-sys = { path = "../cryptoki-sys", version = "0.1.4" }
paste = "1.0.6"
secrecy = "0.8.0"
signature = { version = "2.1.0", optional = true, features = [ "std" ] }

[dev-dependencies]
num-traits = "0.2.14"
Expand All @@ -27,6 +28,8 @@ serial_test = "0.5.1"
testresult = "0.2.0"

[features]
default = [ "signature-traits" ]
psa-crypto-conversions = ["psa-crypto"]
signature-traits = ["signature"]
generate-bindings = ["cryptoki-sys/generate-bindings"]
serde = ["secrecy/serde"]
36 changes: 36 additions & 0 deletions cryptoki/src/session/signing_macing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,16 @@ use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

#[cfg(feature = "signature-traits")]
use signature::Signer;

impl Session {
#[cfg(feature = "signature-traits")]
/// Prepare a signature request which implements the signature::Signer trait.
pub fn prepare_signature<'a>(&'a self, mechanism: &'a Mechanism<'a>, key: ObjectHandle) -> SignatureRequest {
SignatureRequest::new(mechanism, key, self)
}

/// Sign data in single-part
pub fn sign(&self, mechanism: &Mechanism, key: ObjectHandle, data: &[u8]) -> Result<Vec<u8>> {
let mut mechanism: CK_MECHANISM = mechanism.into();
Expand Down Expand Up @@ -86,3 +95,30 @@ impl Session {
}
}
}

#[cfg(feature = "signature-traits")]
#[derive(Debug)]
pub struct SignatureRequest<'sess: 'a, 'a, 'b> {
mechanism: &'a Mechanism<'b>,
key: ObjectHandle,
session: &'sess Session
}

#[cfg(feature = "signature-traits")]
impl<'sess, 'a, 'b> SignatureRequest<'sess, 'a, 'b> {
pub fn new(mechanism: &'a Mechanism<'b>, key: ObjectHandle, session: &'sess Session) -> Self {
SignatureRequest {
mechanism,
key,
session
}
}
}


#[cfg(feature = "signature-traits")]
impl<'sess, 'a, 'b> Signer<Vec<u8>> for SignatureRequest<'sess, 'a, 'b> {
fn try_sign(&self, msg: &[u8]) -> core::result::Result<Vec<u8>, signature::Error> {
self.session.sign(self.mechanism, self.key, msg).map_err(signature::Error::from_source)
}
}

0 comments on commit 507f574

Please sign in to comment.