如何从 HSM 获取私钥来签署 XML 文档
我想签署一个使用 HSM 的 XML 文档。 我加载了密钥库,登录并获取证书,但不知道如何获取用于签名功能的私钥。那么解决方案是什么?
我的代码加载和获取证书。
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();
这里是对 XML 文件进行签名的代码
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);
感谢帮助。我用过
keyEntry = (PrivateKey) keystore.getKey(alias, password);
并通过这个问题。