java - javax.xml.crypto.URIReferenceException:无法解析具有 ID 对象的元素
问题描述
我想通过以下方式对 XML 文件进行数字签名
使用 SHA-256 进行散列的一种方式
规范化方法算法="http://www.w3.org/2001/10/xmlexcc14n#"
- RSA 数字签名
- 2048 位私钥
- W3C 推荐 XML 签名语法
- 封装类型签名。
我遵循了这里提到的 Signature api !
但我收到以下错误
com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException:无法解析带有 ID 对象的元素
我已经为“ID”和 setIdAttributeNS 尝试过 Element.setIdAttributeNode 但没有帮助
下面的行是引发错误的地方
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware ( false );
Document doc = dbFactory.newDocumentBuilder().parse(new FileInputStream(filePath));
String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
// Next, create a Reference to a same-document URI that is an Object element and specify the SHA256 digest algorithm
DigestMethod digestMethod = fac.newDigestMethod(DigestMethod.SHA256, null);
Reference reference = fac.newReference("#CBC",digestMethod);
SignatureMethod signatureMethod = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null);
CanonicalizationMethod canonicalizationMethod = fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
// Create the SignedInfo
SignedInfo si = fac.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
// Create a RSA KeyPair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
// Create a KeyValue containing the RSA PublicKey that was generated
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);
//dsc.setDefaultNamespacePrefix("dsig");
// Create the XMLSignature and sign it
XMLSignature signature = fac.newXMLSignature(si, ki,Collections.singletonList(obj), null, null);
signature.sign(dsc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
错误发生在下面的行
signature.sign(dsc)
解决方案
我添加了以下 2 行,它解决了这个问题。
XMLStructure content = new DOMStructure(doc.getDocumentElement());
XMLObject obj = fac.newXMLObject(Collections.singletonList(content), "CBC", null, null);
推荐阅读
- python - 用户输入后循环通过csv文件提取信息
- python - 没有抛出错误,python 创建空白文件,不知道如何排除故障
- elm - Elm:自定义类型的访问值
- c++ - COM 代理服务器超时
- python - python中多处理,异步和concurrency.futures之间的区别
- plugins - WebSocket 网络插件 Unreal Engine v4.22.3
- php - Vanilo Laravel 7 错误 403 - 在 http://127.0.0.1:8000/admin/customer 中被禁止
- python - sqlite3 正则表达式确实匹配反字符类
- digital-ocean - 在 Digital Ocean 上部署 Ghost One-Click Droplet:验证域时退出代码 1
- html - 如何使 div 和 button 大小相同?