I'm trying to implement some demo of XML signing with a certificate which stored in the HSM.
I found some interesting example from this link: Sign XML Document with X509Certificate2 and modified it to using certificate and key inside the HSM with PKCS11Interop wrapper.
But anyone could give me a suggestion or example to convert ObjectHandle privateKey from HSM to SignedXML.SigningKey
private static void SignXmlWithCertificate(XmlDocument xmlDoc, X509Certificate2 cert, Session session, String alias)
{
SignedXml signedXml = new SignedXml(xmlDoc);
List<ObjectAttribute> template = new List<ObjectAttribute>();
template.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));
template.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_RSA));
template.Add(new ObjectAttribute(CKA.CKA_LABEL, alias));
List<ObjectHandle> foundObjects = session.FindAllObjects(template);
ObjectHandle privateKey = foundObjects[0];
signedXml.SigningKey = privateKey; //Here is where I stuck.
In the example from above external link. They using a certificate which combined private key. Then they can use like this.
signedXml.SigningKey = cert.PrivateKey;
But the certificate that I'm using haven't content of private key inside. Please give me some suggestion.
You need to implement custom class inherited from
System.Security.Cryptography.RSA
class, use Pkcs11Interop in its implementation and then use instance of your custom class as aSigningKey
.You can implement it yourself or you can use Pkcs11Interop.X509Store library which provides easy to use PKCS#11 based X.509 certificate store and contains
Pkcs11RsaProvider
class inherited fromSystem.Security.Cryptography.RSA
class. There's also a code sample available which demonstrates its usage withSignedXml
class.You need to implement custom class inherited from System.Security.Cryptography.Xml.SignedXml like this
and then you need to create interface like this
then implement it by Pkcs11Interop like this
then call this method to sign xml
and this code to verify