Example usage for javax.xml.crypto.dsig Reference getCalculatedDigestValue

List of usage examples for javax.xml.crypto.dsig Reference getCalculatedDigestValue

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig Reference getCalculatedDigestValue.

Prototype

byte[] getCalculatedDigestValue();

Source Link

Document

Returns the calculated digest value of this Reference after a validation operation.

Usage

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
 * Used to verify an enveloped digital signature
 *
 * @param doc a Document object containing the xml with the signature
 * @param keyStorePath a String containing the path to the KeyStore
 * @param keyStorePW a String containing the KeyStore password
 * @param verifyAlias a String containing the alias of the public key used for verification
 * @return True if signature passes verification, False otherwise
 *///from ww  w  .  j a  va2  s  .c  o  m
public static boolean verifySignature(Document doc, String keyStorePath, String keyStorePW,
        String verifyAlias) {
    boolean coreValidation = false;
    PublicKey publicKey = ClientUtil.getPublicKeyByAlias(keyStorePath, keyStorePW, verifyAlias);
    if (publicKey == null) {
        logger.error(
                "Public key was null when verifying signature. Ensure keystore configuration values are set properly.");
        return false;
    }
    try {
        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (nl.getLength() == 0) {
            logger.error("No XML Digital Signature was found. The document was discarded.");
            return false;
        }
        Node signatureNode = nl.item(nl.getLength() - 1);
        DOMValidateContext valContext = new DOMValidateContext(publicKey, signatureNode);
        valContext.setURIDereferencer(new MyURIDereferencer(signatureNode.getParentNode()));
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        coreValidation = signature.validate(valContext);
        if (!coreValidation) {
            // for testing/debugging when validation fails...
            logger.error("Digital Signature Core Validation failed.");
            boolean signatureValidation = signature.getSignatureValue().validate(valContext);
            logger.debug("Digital Signature Validation: " + signatureValidation);
            @SuppressWarnings("rawtypes")
            Iterator i = signature.getSignedInfo().getReferences().iterator();
            for (int j = 0; i.hasNext(); j++) {
                Reference ref = (Reference) i.next();
                boolean referenceValidation = ref.validate(valContext);
                logger.debug("Digital Signature Reference Validation: " + referenceValidation);
                byte[] calculatedDigestValue = ref.getCalculatedDigestValue();
                byte[] digestValue = ref.getDigestValue();
                String cdvString = new String(Base64.encodeBase64(calculatedDigestValue));
                logger.debug("Digital Signature Calculated Digest Value: " + cdvString);
                String dvString = new String(Base64.encodeBase64(digestValue));
                logger.debug("Digital Signature Digest Value: " + dvString);
            }
        }
    } catch (MarshalException e) {
        logger.error("MarshalException when attempting to verify a digital signature.");
    } catch (XMLSignatureException e) {
        logger.error("XMLSignature Exception when attempting to verify a digital signature.");
    }
    return coreValidation;
}

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * Verifica si una firma XML embedida es válida según define
 * el est&aacute;ndar XML Signature (<a
 * href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core
 * Validation</a>), y si el certificado era v&aacute;lido en la fecha dada.
 * <p>/*from  w  w  w  .  ja v a  2 s .c o m*/
 * 
 * Esta rutina <b>NO</b> verifica si el certificado embedido en
 * &lt;KeyInfo&gt; es v&aacute;lido (eso debe verificarlo con la autoridad
 * certificadora que emiti&oacute; el certificado), pero si verifica que la
 * llave utilizada para verificar corresponde a la contenida en el
 * certificado.
 * 
 * @param xml
 *            el nodo &lt;Signature&gt;
 * @param date
 *            una fecha en la que se verifica la validez del certificado
 * @return el resultado de la verificaci&oacute;n
 * 
 * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext)
 * @see cl.nic.dte.VerifyResult
 * @see cl.nic.dte.extension.DTEDefTypeExtensionHandler
 * @see #getCertificate(XMLSignature)
 */
@SuppressWarnings("unchecked")
public static VerifyResult verifySignature(XMLSignature signature, DOMValidateContext valContext) {

    try {

        KeyValueKeySelector ksel = (KeyValueKeySelector) valContext.getKeySelector();
        X509Certificate x509 = getCertificate(signature);

        // Verifica que un certificado bien embedido
        if (x509 == null) {
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                    Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NO509")));
        }

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

        // Check core validation status
        if (coreValidity == false) {
            boolean sv = signature.getSignatureValue().validate(valContext);
            if (!sv)
                return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                        Utilities.verificationLabels.getString("XML_SIGNATURE_BAD_VALUE"));

            // check the validation status of each Reference
            String message = "";

            for (Reference ref : (List<Reference>) signature.getSignedInfo().getReferences()) {
                if (!ref.validate(valContext)) {
                    message += Utilities.verificationLabels.getString("XML_SIGNATURE_BAD_REFERENCE");
                    message = message.replaceAll("%1",
                            new String(Base64.encodeBase64(ref.getCalculatedDigestValue())));
                    message = message.replaceAll("%2", new String(Base64.encodeBase64(ref.getDigestValue())));
                    message += "\n";
                }
            }
            return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message);
        }

        // Verifica que la llave del certificado corresponde a la usada para
        // la firma
        if (!ksel.getPk().equals(x509.getPublicKey())) {
            String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_BADKEY");
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message));
        }

        return new VerifyResult(VerifyResult.XML_SIGNATURE_OK, true, null);
    } catch (XMLSignatureException e) {
        return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNKNOWN") + ": " + e.getMessage()));
    }

}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

private boolean verifySignature(Element element, PublicKey validatingKey,
        AtomicReference<String> OutReadableErrorMessage) {
    if (OutReadableErrorMessage == null) {
        OutReadableErrorMessage = new AtomicReference<String>();
    }/*from   ww  w  .  ja  v  a2  s. c  om*/
    XMLSignatureFactory fac = initXMLSigFactory();
    NodeList nl = element.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Cannot find Signature element");
    }
    DOMValidateContext valContext = new DOMValidateContext(validatingKey, nl.item(0));
    try {
        valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        boolean coreValidity = signature.validate(valContext);
        // Check core validation status.
        if (coreValidity == false) {
            logger.warn("Signature failed core validation");
            boolean sv = signature.getSignatureValue().validate(valContext);
            logger.debug("signature validation status: " + sv);
            OutReadableErrorMessage
                    .set("signature validation failed: " + sv + "." + OutReadableErrorMessage.get());
            // Check the validation status of each Reference.
            @SuppressWarnings("unchecked")
            Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator();
            //System.out.println("---------------------------------------------");
            for (int j = 0; i.hasNext(); j++) {
                Reference ref = (Reference) i.next();
                boolean refValid = ref.validate(valContext);
                logger.debug(j);
                logger.debug("ref[" + j + "] validity status: " + refValid);
                if (!refValid) {
                    OutReadableErrorMessage
                            .set("signature reference " + j + " invalid. " + OutReadableErrorMessage.get());
                }
                logger.debug("Ref type: " + ref.getType() + ", URI: " + ref.getURI());
                for (Object xform : ref.getTransforms()) {
                    logger.debug("Transform: " + xform);
                }
                String calcDigValStr = digestToString(ref.getCalculatedDigestValue());
                String expectedDigValStr = digestToString(ref.getDigestValue());
                logger.warn("    Calc Digest: " + calcDigValStr);
                logger.warn("Expected Digest: " + expectedDigValStr);
                if (!calcDigValStr.equalsIgnoreCase(expectedDigValStr)) {
                    OutReadableErrorMessage.set(
                            "digest mismatch for signature ref " + j + "." + OutReadableErrorMessage.get());
                }
            }
        } else {
            logger.info("Signature passed core validation");
        }
        return coreValidity;
    } catch (Exception e) {
        OutReadableErrorMessage
                .set("signature validation failed: " + e.getMessage() + OutReadableErrorMessage.get());
        logger.fatal(e);
        return false;
    }
}