Skip to content

Commit

Permalink
rsa: implement prehash signer for RSA-PKCS
Browse files Browse the repository at this point in the history
  • Loading branch information
baloo committed Feb 12, 2025
1 parent c5c4da9 commit 670704d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use crate::{
uuid,
wrap::{self, commands::*},
};
use digest::Output;
use sha2::Sha256;
use std::{
sync::{Arc, Mutex},
Expand Down Expand Up @@ -1030,6 +1031,22 @@ impl Client {
.into())
}

/// Compute an RSASSA-PKCS#1v1.5 signature of the SHA-256 hash of the given prehash.
///
/// <https://developers.yubico.com/YubiHSM2/Commands/Sign_Pkcs1.html>
pub(crate) fn sign_rsa_pkcs1v15_prehash<S: SignatureAlgorithm>(
&self,
key_id: object::Id,
prehash: Output<S>,
) -> Result<rsa::pkcs1::Signature, Error> {
Ok(self
.send_command(SignPkcs1Command {
key_id,
digest: prehash.to_vec(),
})?
.into())
}

/// Compute an RSASSA-PKCS#1v1.5 signature of the SHA-256 hash of the given data.
///
/// <https://developers.yubico.com/YubiHSM2/Commands/Sign_Pkcs1.html>
Expand Down
27 changes: 27 additions & 0 deletions src/rsa/pkcs1/signer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{object, rsa::SignatureAlgorithm, Client};
use digest::Output;
use rsa::{
pkcs1v15::{RsaSignatureAssociatedOid, Signature, VerifyingKey},
RsaPublicKey,
Expand Down Expand Up @@ -85,3 +86,29 @@ where
const SIGNATURE_ALGORITHM_IDENTIFIER: AlgorithmIdentifier<Self::Params> =
<VerifyingKey<S> as SignatureAlgorithmIdentifier>::SIGNATURE_ALGORITHM_IDENTIFIER;
}

impl<S> signature::hazmat::PrehashSigner<Signature> for Signer<S>
where
S: SignatureAlgorithm,
{
fn sign_prehash(&self, prehash: &[u8]) -> Result<Signature, Error> {
let buf = Output::<S>::try_from(prehash).map_err(|_| Error::new())?;

self.client
.sign_rsa_pkcs1v15_prehash::<S>(self.signing_key_id, buf)?
.as_slice()
.try_into()
}
}

impl<S> signature::DigestSigner<S, Signature> for Signer<S>
where
S: SignatureAlgorithm,
{
fn try_sign_digest(&self, digest: S) -> Result<Signature, Error> {
self.client
.sign_rsa_pkcs1v15_prehash::<S>(self.signing_key_id, digest.finalize())?
.as_slice()
.try_into()
}
}

0 comments on commit 670704d

Please sign in to comment.