Skip to content

Commit

Permalink
fixup updates
Browse files Browse the repository at this point in the history
Signed-off-by: Arthur Gautier <[email protected]>
  • Loading branch information
baloo committed Nov 11, 2024
1 parent 7f4cd92 commit af53442
Show file tree
Hide file tree
Showing 9 changed files with 774 additions and 45 deletions.
640 changes: 633 additions & 7 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
[workspace]
members = ["cryptoki", "cryptoki-sys", "cryptoki-rustcrypto"]

[patch.crates-io]
pkcs12 = { git = "https://github.com/RustCrypto/formats.git" }
rsa = { path = "../RSA" }
27 changes: 14 additions & 13 deletions cryptoki-rustcrypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,23 @@ repository = "https://github.com/parallaxsecond/rust-cryptoki"

[dependencies]
cryptoki = { path = "../cryptoki", version = "0.7.0" }
der = "=0.8.0-pre.0"
ecdsa = "=0.17.0-pre.5"
p224 = { version = "=0.14.0-pre", features = ["pkcs8"] }
p256 = { version = "=0.14.0-pre.0", features = ["pkcs8"] }
p384 = { version = "=0.14.0-pre", features = ["pkcs8"] }
k256 = { version = "=0.14.0-pre.0", features = ["pkcs8"] }
rsa = "=0.10.0-pre.1"
signature = { version = "=2.3.0-pre.3", features = ["derive", "digest"] }
sha1 = { version = "=0.11.0-pre.3", features = ["oid"] }
sha2 = { version = "=0.11.0-pre.3", features = ["oid"] }
spki = "=0.8.0-pre.0"
x509-cert = "=0.3.0-pre"
der = "=0.8.0-rc.1"
ecdsa = "=0.17.0-pre.9"
#p224 = { version = "=0.14.0-pre.2", features = ["pkcs8"] }
p256 = { version = "=0.14.0-pre.2", features = ["pkcs8"] }
p384 = { version = "=0.14.0-pre.2", features = ["pkcs8"] }
k256 = { version = "=0.14.0-pre.2", features = ["pkcs8"] }
pkcs12 = { version = "=0.2.0-pre" }
rsa = { version = "=0.10.0-pre.3", features = ["sha2"] }
signature = { version = "=2.3.0-pre.4", features = ["derive", "digest"] }
sha1 = { version = "=0.11.0-pre.4", features = ["oid"] }
sha2 = { version = "=0.11.0-pre.4", features = ["oid"] }
spki = "=0.8.0-rc.1"
x509-cert = "=0.3.0-pre.0"
thiserror = "1.0"

[dev-dependencies]
rand = "0.8.5"
serial_test = "0.5.1"
testresult = "0.2.0"
x509-cert = { version = "=0.3.0-pre", features = ["builder"] }
x509-cert = { version = "=0.3.0-pre.0", features = ["builder"] }
2 changes: 1 addition & 1 deletion cryptoki-rustcrypto/src/ecdsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ macro_rules! impl_sign_algorithm {
};
}

impl_sign_algorithm!(p224::NistP224);
//impl_sign_algorithm!(p224::NistP224);
impl_sign_algorithm!(p256::NistP256);
impl_sign_algorithm!(p384::NistP384);
impl_sign_algorithm!(k256::Secp256k1);
Expand Down
42 changes: 40 additions & 2 deletions cryptoki-rustcrypto/src/rsa/pkcs1v15.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
// Copyright 2023 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0

use cryptoki::object::{Attribute, AttributeType, KeyType, ObjectClass, ObjectHandle};
use cryptoki::{
mechanism::Mechanism,
object::{Attribute, AttributeType, KeyType, ObjectClass, ObjectHandle},
};
use rsa::pkcs1v15::{RsaSignatureAssociatedOid, Signature, VerifyingKey};
use spki::{AlgorithmIdentifier, AssociatedAlgorithmIdentifier, SignatureAlgorithmIdentifier};
use spki::{
der::{asn1::OctetString, oid::AssociatedOid, referenced::RefToOwned, AnyRef, Encode},
AlgorithmIdentifier, AlgorithmIdentifierRef, AssociatedAlgorithmIdentifier,
SignatureAlgorithmIdentifier,
};
use std::convert::TryFrom;

use super::{read_key, DigestSigning, Error};
Expand Down Expand Up @@ -110,3 +117,34 @@ where
const SIGNATURE_ALGORITHM_IDENTIFIER: AlgorithmIdentifier<Self::Params> =
<VerifyingKey<D> as SignatureAlgorithmIdentifier>::SIGNATURE_ALGORITHM_IDENTIFIER;
}

impl<D, S> signature::hazmat::PrehashSigner<Signature> for Signer<D, S>
where
S: SessionLike,
D: DigestSigning + RsaSignatureAssociatedOid,
{
fn sign_prehash(&self, prehash: &[u8]) -> Result<Signature, signature::Error> {
let payload = pkcs12::DigestInfo {
algorithm: (AlgorithmIdentifierRef {
oid: <D as AssociatedOid>::OID,
parameters: Some(AnyRef::NULL),
})
.ref_to_owned(),
digest: OctetString::new(prehash).unwrap(),
};

let msg = payload.to_der().unwrap();
println!("msg: {msg:x?}");

let bytes = self
.session
.sign(&Mechanism::RsaPkcs, self.private_key, &msg)
.map_err(Error::Cryptoki)
.map_err(Box::new)
.map_err(signature::Error::from_source)?;

let signature = Signature::try_from(bytes.as_slice())?;

Ok(signature)
}
}
6 changes: 4 additions & 2 deletions cryptoki-rustcrypto/src/x509.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ where
template.push(Attribute::CertificateType(CertificateType::X_509));
template.push(Attribute::Token(true));
template.push(Attribute::Value(self.to_der()?));
if !self.tbs_certificate.subject.is_empty() {
template.push(Attribute::Subject(self.tbs_certificate.subject.to_der()?));
if !self.tbs_certificate().subject().is_empty() {
template.push(Attribute::Subject(
self.tbs_certificate().subject().to_der()?,
));
}

Ok(session.create_object(&template)?)
Expand Down
5 changes: 3 additions & 2 deletions cryptoki-rustcrypto/tests/ecdsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,9 @@ fn test_import() -> TestResult {

let template = vec![Attribute::Token(false), Attribute::Label(label.to_vec())];

let private_handle = private.put_key(&session, template.clone())?;
let public_handle = private.verifying_key().put_key(&session, template)?;
let private_handle = p256::SecretKey::from(&private).put_key(&session, template.clone())?;
let public_handle =
p256::PublicKey::from(private.verifying_key()).put_key(&session, template)?;

// data to sign
let data = [0xFF, 0x55, 0xDD];
Expand Down
67 changes: 62 additions & 5 deletions cryptoki-rustcrypto/tests/rsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ use crate::common::USER_PIN;
use common::init_pins;
use cryptoki::{mechanism::Mechanism, object::Attribute, session::UserType, types::AuthPin};
use cryptoki_rustcrypto::rsa::{pkcs1v15, pss};
use rand::{thread_rng, RngCore};
use serial_test::serial;
use signature::{Keypair, Signer, Verifier};
use sha2::{Digest, Sha256};
use signature::{hazmat::PrehashSigner, Keypair, Signer, Verifier};
use testresult::TestResult;

#[test]
Expand Down Expand Up @@ -49,8 +51,7 @@ fn pkcs1v15_sign_verify() -> TestResult {
// data to sign
let data = [0xFF, 0x55, 0xDD];

let signer =
pkcs1v15::Signer::<sha2::Sha256, _>::new(&session, label).expect("Lookup keys from HSM");
let signer = pkcs1v15::Signer::<Sha256, _>::new(&session, label).expect("Lookup keys from HSM");

let signature = signer.sign(&data);

Expand Down Expand Up @@ -102,8 +103,7 @@ fn pss_sign_verify() -> TestResult {
// data to sign
let data = [0xFF, 0x55, 0xDD];

let signer =
pss::Signer::<sha2::Sha256, _>::new(&session, label).expect("Lookup keys from HSM");
let signer = pss::Signer::<Sha256, _>::new(&session, label).expect("Lookup keys from HSM");

let signature = signer.sign(&data);

Expand All @@ -116,3 +116,60 @@ fn pss_sign_verify() -> TestResult {

Ok(())
}

#[test]
#[serial]
fn pkcs1v15_sign_verify_prehashed() -> 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())))?;

// get mechanism
let mechanism = Mechanism::RsaPkcsKeyPairGen;

let public_exponent: Vec<u8> = vec![0x01, 0x00, 0x01];
let modulus_bits = 1024;

let label = b"demo-signer";

// pub key template
let pub_key_template = vec![
Attribute::Token(true),
Attribute::Private(false),
Attribute::Label(label.to_vec()),
Attribute::PublicExponent(public_exponent),
Attribute::ModulusBits(modulus_bits.into()),
];

// priv key template
let priv_key_template = vec![Attribute::Token(true), Attribute::Label(label.to_vec())];

// generate a key pair
let (public, private) =
session.generate_key_pair(&mechanism, &pub_key_template, &priv_key_template)?;

// data to sign
let mut data = [0u8; 7123];
thread_rng().fill_bytes(&mut data[..]);

let prehashed = Sha256::digest(&data[..]);

let signer = pkcs1v15::Signer::<Sha256, _>::new(&session, label).expect("Lookup keys from HSM");

let signature1 = signer.sign(&data);
let signature2 = signer.sign_prehash(&prehashed).expect("Sign prehash");

let verifying_key = signer.verifying_key();
verifying_key.verify(&data, &signature1)?;
verifying_key.verify(&data, &signature2)?;

// delete keys
session.destroy_object(public)?;
session.destroy_object(private)?;

Ok(())
}
26 changes: 13 additions & 13 deletions cryptoki-rustcrypto/tests/x509-ca.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use spki::SubjectPublicKeyInfoOwned;
use std::{str::FromStr, time::Duration};
use testresult::TestResult;
use x509_cert::{
builder::{Builder, CertificateBuilder, Profile},
builder::{profile::cabf, Builder, CertificateBuilder},
name::Name,
serial_number::SerialNumber,
time::Validity,
Expand Down Expand Up @@ -66,16 +66,15 @@ fn pss_create_ca() -> TestResult {

let serial_number = SerialNumber::from(42u32);
let validity = Validity::from_now(Duration::new(5, 0)).unwrap();
let profile = Profile::Root;
let subject =
Name::from_str("CN=World domination corporation,O=World domination Inc,C=US").unwrap();
let pub_key = SubjectPublicKeyInfoOwned::from_key(signer.verifying_key()).unwrap();
let profile = cabf::Root::new(false, subject).expect("Create root profile");
let pub_key = SubjectPublicKeyInfoOwned::from_key(&signer.verifying_key()).unwrap();

let builder =
CertificateBuilder::new(profile, serial_number, validity, subject, pub_key, &signer)
.expect("Create certificate");
let builder = CertificateBuilder::new(profile, serial_number, validity, pub_key)
.expect("Create certificate");

let certificate = builder.build().unwrap();
let certificate = builder.build(&signer).unwrap();

let pem = certificate.to_pem(LineEnding::LF).expect("generate pem");
println!("{}", pem);
Expand Down Expand Up @@ -132,16 +131,17 @@ fn ecdsa_create_ca() -> TestResult {

let serial_number = SerialNumber::from(42u32);
let validity = Validity::from_now(Duration::new(5, 0)).unwrap();
let profile = Profile::Root;
let subject =
Name::from_str("CN=World domination corporation,O=World domination Inc,C=US").unwrap();
let pub_key = SubjectPublicKeyInfoOwned::from_key(signer.verifying_key()).unwrap();
let profile = cabf::Root::new(false, subject).expect("create root profile");
let pub_key = SubjectPublicKeyInfoOwned::from_key(&signer.verifying_key()).unwrap();

let builder =
CertificateBuilder::new(profile, serial_number, validity, subject, pub_key, &signer)
.expect("Create certificate");
let builder = CertificateBuilder::new(profile, serial_number, validity, pub_key)
.expect("Create certificate");

let certificate = builder.build::<p256::ecdsa::DerSignature>().unwrap();
let certificate = builder
.build::<_, p256::ecdsa::DerSignature>(&signer)
.unwrap();

let pem = certificate.to_pem(LineEnding::LF).expect("generate pem");
println!("{}", pem);
Expand Down

0 comments on commit af53442

Please sign in to comment.