Java 使用 public 密钥验证 xml 数字签名

Java Verify xml digital signature using public key

我有一份已由 private_key.pfx 签名的 xml 文档。

现在我有一个 public_key.cert 文件,它从 :

开始
====== BEGIN OF =======
jksbfjkbckcnJKNBCKSJJksncs==

====== END OF========== 

现在,我想使用我的 public_key.cer

验证签名的 xml 文档

我该怎么做?

请帮忙

您需要在签名文档中查找 <Signature> 元素。 Java XML 数字签名 API 中有一些方法可以用来验证签名,例如 XMLSignature.validate().

如果您查看这篇文章:Programming With the Java XML Digital Signature API

key steps in validating an XML signature.

// Find Signature element.
NodeList nl =
    doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
    throw new Exception("Cannot find Signature element");
}

// Create a DOMValidateContext and specify a KeySelector
// and document context.
DOMValidateContext valContext = new DOMValidateContext
    (new X509KeySelector(), nl.item(0));

// Unmarshal the XMLSignature.
XMLSignature signature = fac.unmarshalXMLSignature(valContext);

// Validate the XMLSignature.
boolean coreValidity = signature.validate(valContext);

First, you must find the location of the Signature element that you wish to validate. One way to do this is to use the DOM getElementsByTagNameNS method as shown in Code Sample 5. The second block of code creates a DOMValidateContext object containing a KeySelector object and a reference to the Signature element. The purpose of the KeySelector object is to obtain the public key using the information in the KeyInfo element and hand it back to be used as the validation key. The next section will discuss KeySelectors in more detail. The last two lines of code unmarshal and validate the signature. The validate method returns true if the signature is valid and false if it is invalid.