我正在创建一个WebService来签署一种XML。我正在为此使用智能卡(A3证书)。 在对XML签名时,将显示一个Enter PIN对话框。 是否可以隐藏此对话框并在内部插入此PIN? 这是我的代码:
public static String getAssinaturaString(String xml) {
try {
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
List<Transform> transforms = new ArrayList<>();
transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
transforms.add(
fac.newTransform("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", (TransformParameterSpec) null));
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA256, null), transforms, null,
null);
// Create the SignedInfo.
SignedInfo si = fac.newSignedInfo(
fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null),
fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
(SignatureMethodParameterSpec) null),
Collections.singletonList(ref));
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(CERT_ALIAS,
new KeyStore.PasswordProtection(CERT_PASSWORD.toCharArray()));
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
KeyInfoFactory kif = fac.getKeyInfoFactory();
List<Serializable> x509Content = new ArrayList<Serializable>();
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc); //here show the dialog
StringWriter xmlAssinado = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(xmlAssinado));
return xmlAssinado.toString();
} catch (Exception e) {
e.getStackTrace();
return null;
}
}
我尝试了这个示例,但是没有成功: Signing documents with SunMSCAPI and suppressing the “Enter PIN” dialog