使用java中的公钥验证签名的XML

时间:2016-06-30 04:34:24

标签: java cryptography digital-signature public-key verify

嘿伙计我已经使用私钥签署了一个XML,现在我想用公钥验证它是用于签署XML的私钥。

我的verify()函数位于

之下
       public boolean verify(String signedXml) {

    boolean verificationResult = false;

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document signedDocument = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(signedXml)));

        NodeList nl = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (nl.getLength() == 0) {
            throw new IllegalArgumentException("Cannot find Signature element");
        }

        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

        DOMValidateContext valContext = new DOMValidateContext(getCertificateFromFile(publicKeyFile).getPublicKey(), nl.item(0));
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);

        verificationResult = signature.validate(valContext);

    } catch (Exception e) {
        System.out.println("Error while verifying digital siganature" + e.getMessage());
        e.printStackTrace();
    }

    return verificationResult;
}

getCertificateFromFile()是

       public X509Certificate getCertificateFromFile(String certificateFile) throws GeneralSecurityException, IOException {
    FileInputStream fis = null;
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
        fis = new FileInputStream(certificateFile);
        return (X509Certificate) certFactory.generateCertificate(fis);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

}

当我使用公钥(.cer)验证我的签名XML时,无论我在签名XML中做了多少更改,它都会返回true,我甚至使用了不同的私钥,它仍然是真的! 有什么建议吗?

0 个答案:

没有答案