Generating a CSR from a PKCS11

30 views
Skip to first unread message

olivie...@gmail.com

unread,
Jul 17, 2019, 9:20:26 AM7/17/19
to Pkcs11Interop
public byte[] GeneratePkcs10(IObjectHandle publicKeyHandle, IObjectHandle privateKeyHandle, string subjectDistinguishedName, CKM hashAlgorithm)
{
string signatureAlgorihtm = null;
switch (hashAlgorithm)
{
case CKM.CKM_MD2_RSA_PKCS:
signatureAlgorihtm = PkcsObjectIdentifiers.MD2WithRsaEncryption.Id;
break;
case CKM.CKM_MD5_RSA_PKCS:
signatureAlgorihtm = PkcsObjectIdentifiers.MD5WithRsaEncryption.Id;
break;
case CKM.CKM_SHA1_RSA_PKCS:
signatureAlgorihtm = PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id;
break;
case CKM.CKM_SHA256_RSA_PKCS:
signatureAlgorihtm = PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id;
break;
case CKM.CKM_SHA384_RSA_PKCS:
signatureAlgorihtm = PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id;
break;
case CKM.CKM_SHA512_RSA_PKCS:
signatureAlgorihtm = PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id;
break;
case CKM.CKM_SHA224_RSA_PKCS:
signatureAlgorihtm = PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id;
break;
default:
throw new NotSupportedException($"L'algorithme {hashAlgorithm} n'est pas supporté");
}

// Read public key attributes
var publicKey = Session.GetAttributesValues<HSMRSAPublicKey>(publicKeyHandle);
if (CKK.CKK_RSA != publicKey.KeyType)
throw new NotSupportedException("Currently only RSA keys are supported");

// Create instance of RsaKeyParameters class usable for BouncyCastle
var publicKeyParameters = new RsaKeyParameters(false, publicKey.Modulus, publicKey.PublicExponent);

// Determine algorithms
IMechanism mechanism = Session.Factories.MechanismFactory.Create(hashAlgorithm);

// Generate and sign PKCS#10 request
Pkcs10CertificationRequestDelaySigned pkcs10 = new Pkcs10CertificationRequestDelaySigned(signatureAlgorihtm, new X509Name(subjectDistinguishedName), publicKeyParameters, null);
byte[] signature = Session.Sign(mechanism, privateKeyHandle, pkcs10.GetDataToSign());
pkcs10.SignRequest(new DerBitString(signature));
return pkcs10.GetDerEncoded();
}
Reply all
Reply to author
Forward
0 new messages