这些是标准的XML签名。见 关于“XML签名语法和处理”的W3文档 对于规范如何做到这一点。谷歌上的快速搜索引导了Oracle编写的关于Java中XML签名集成的方法: XML数字签名API 。如果您还有其他问题,请告诉我们您的尝试。
这是解决方案:
我在这个链接上找到它 http://mail-archives.apache.org/mod_mbox/santuario-dev/200907.mbox/%3C4A704241.9060806@sun.com%3E 问题是RSA-SHA256算法:
这是结果代码:
private static Document sign(Document doc) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FileNotFoundException, TransformerException { String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); DigestMethod digestMethod = fac.newDigestMethod(DigestMethod.SHA256, null); Transform transform = fac.newTransform(ENVELOPED, (TransformParameterSpec) null); Reference reference = fac.newReference("", digestMethod, singletonList(transform), null, null); SignatureMethod signatureMethod = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null); CanonicalizationMethod canonicalizationMethod = fac.newCanonicalizationMethod(EXCLUSIVE, (C14NMethodParameterSpec) null); // Create the SignedInfo SignedInfo si = fac.newSignedInfo(canonicalizationMethod, signatureMethod, singletonList(reference)); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair kp = kpg.generateKeyPair(); KeyInfoFactory kif = fac.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(kp.getPublic()); // Create a KeyInfo and add the KeyValue to it KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); // output the resulting document OutputStream os; os = new FileOutputStream("xmlOut.xml"); trans.transform(new DOMSource(doc), new StreamResult(os)); return doc; }
你得到了 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> ,因为那就是你要求的: fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null) 。 正如你想的那样 https://blogs.oracle.com/mullan/entry/using_stronger_xml_signature_algorithms 状态, fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", (SignatureMethodParameterSpec) null) 会得到你 <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" /> 。
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null)
fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", (SignatureMethodParameterSpec) null)
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />