How to get private key from HSM to sign XML doc
I want to sign a XML document used HSM. I loaded keystore, login and get certificate, but don't know how to get privateKey to use in sign function. So what's solution for it?
My code to load and get cerificate.
String library = "mypath/cs_pkcs11_R2.dll";
StringBuilder builder = new StringBuilder();
builder.append("name=" + nameLib);
builder.append(System.getProperty("line.separator"));
builder.append("library=\"" + library + "\"");
builder.append(System.getProperty("line.separator"));
builder.append("slot=" + slot);
Init.init();
ByteArrayInputStream bais = new ByteArrayInputStream(builder.toString().getBytes());
provider = new SunPKCS11(bais);
Security.addProvider(provider);
keystore = KeyStore.getInstance("PKCS11");
keystore.load(null, password);
Enumeration<String> aliases = keystore.aliases();
String alias;
Certificate cert = null;
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
System.out.println("alias name: " + alias);
Certificate[] certChain = keystore.getCertificateChain(alias);
if (certChain == null) {
continue;
}
cert = certChain[0];
if (cert instanceof X509Certificate) {
// avoid expired certificate
((X509Certificate) cert).checkValidity();
}
X509Certificate c1 = (X509Certificate) cert;
PublicKey pubKey = c1.getPublicKey();
And here it code to sign XML file
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = null;
XmlSigner xmlsign = new XmlSigner();
try {
doc = dbf.newDocumentBuilder().parse(new FileInputStream("myPath\\xml_Input.xml"));
} catch (IOException e) {
e.printStackTrace();
//System.exit(5);
}
Element documentRoot = doc.getDocumentElement();
Element signatureElement = xmlsign.getSignatureElement(doc);
String digestMethod = "http://www.w3.org/2000/09/xmldsig#sha1";
String signatureMethod= "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
XMLSignature signature = new XMLSignature(doc, "#", signatureMethod, provider);
Transforms contentTransforms = new Transforms(doc);
contentTransforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
contentTransforms.addTransform("http://www.w3.org/2001/10/xml-exc-c14n#");
signature.addDocument(xmlsign.getSignatureReferenceUri("ID", documentRoot), contentTransforms, digestMethod);
signatureElement = signature.getElement();
xmlsign.addSignatureELement("LAST", documentRoot, signatureElement);
signature.sign(signKey); <- need privateKey here
xmlsign.populateKeyInfo(doc, signature.getKeyInfo(), cert);
signatureElement = xmlsign.getSignatureElement(doc);