Example usage for javax.xml.crypto MarshalException getMessage

List of usage examples for javax.xml.crypto MarshalException getMessage

Introduction

In this page you can find the example usage for javax.xml.crypto MarshalException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

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>/* www.j a  v a 2 s.co  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)
 */
public static VerifyResult verifySignature(Node xml) {

    try {

        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        KeyValueKeySelector ksel = new KeyValueKeySelector();

        DOMValidateContext valContext = new DOMValidateContext(ksel, xml);

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

        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")));
        }

        return (verifySignature(signature, valContext));
    } catch (MarshalException e1) {
        return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNMARSHAL") + ": "
                        + e1.getMessage()));
    }

}

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

/**
 * Verifica si una firma XML embedida es v&aacute;lida seg&uacute;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 . j a v  a  2  s.co 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)
 */
public static VerifyResult verifySignature(Node xml, Date date) {

    try {

        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        KeyValueKeySelector ksel = new KeyValueKeySelector();

        DOMValidateContext valContext = new DOMValidateContext(ksel, xml);

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

        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")));
        }

        try {
            // Valida que en la fecha dada el certificado era va'lido
            x509.checkValidity(date);
        } catch (CertificateExpiredException e) {
            String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID");
            message = message.replaceAll("%1", DateFormat.getDateInstance().format(date));
            message = message.replaceAll("%2", DateFormat.getDateInstance().format(x509.getNotBefore()));
            message = message.replaceAll("%3", DateFormat.getDateInstance().format(x509.getNotAfter()));
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message));
        } catch (CertificateNotYetValidException e) {
            String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID");
            message = message.replaceAll("%1", DateFormat.getDateInstance().format(date));
            message = message.replaceAll("%2", DateFormat.getDateInstance().format(x509.getNotBefore()));
            message = message.replaceAll("%3", DateFormat.getDateInstance().format(x509.getNotAfter()));
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message));
        }

        return (verifySignature(signature, valContext));
    } catch (MarshalException e1) {
        return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNMARSHAL") + ": "
                        + e1.getMessage()));
    }

}

From source file:be.fedict.eid.dss.document.xml.XMLDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] documentData, byte[] originalDocument) throws Exception {
    Document document = this.documentBuilder.parse(new ByteArrayInputStream(documentData));

    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (0 == signatureNodeList.getLength()) {
        LOG.debug("no XML signature found");
        return signatureInfos;
    }/* w  ww .ja v a2  s.  co  m*/

    XAdESValidation xadesValidation = new XAdESValidation(this.context);

    for (int signatureNodeIdx = 0; signatureNodeIdx < signatureNodeList.getLength(); signatureNodeIdx++) {
        /*
         * Check signature.
         */
        Element signatureElement = (Element) signatureNodeList.item(signatureNodeIdx);
        xadesValidation.prepareDocument(signatureElement);

        KeyInfoKeySelector keyInfoKeySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keyInfoKeySelector, signatureElement);
        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM",
                new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());
        XMLSignature xmlSignature;
        try {
            xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        } catch (MarshalException e) {
            LOG.error("XML signature marshalling error: " + e.getMessage(), e);
            continue;
        }
        LOG.debug("validating signature: " + xmlSignature.getId());
        boolean signatureValid = xmlSignature.validate(domValidateContext);
        LOG.debug("signature valid: " + signatureValid);
        if (!signatureValid) {
            LOG.error("invalid signature");
            throw new RuntimeException("invalid signature");
        }

        if (null != originalDocument) {
            Document originalDomDocument = XAdESUtils.loadDocument(originalDocument);
            LOG.debug("performing original document verification");
            verifyCoSignatureReference(xmlSignature, originalDomDocument);
            LOG.debug("original document verified");
        } else {
            /*
             * We can still check whether the co-signature ds:Reference is
             * indeed doing a co-signature.
             */
            verifyCoSignatureReference(xmlSignature, document);
        }

        X509Certificate signingCertificate = keyInfoKeySelector.getCertificate();
        SignatureInfo signatureInfo = xadesValidation.validate(document, xmlSignature, signatureElement,
                signingCertificate);
        signatureInfos.add(signatureInfo);
    }
    return signatureInfos;
}

From source file:be.fedict.eid.tsl.TrustServiceList.java

public X509Certificate verifySignature() {
    if (null == this.tslDocument) {
        LOG.debug("first save the document");
        return null;
    }//from   w w  w  .java2  s .c om

    Node signatureNode = getSignatureNode();
    if (null == signatureNode) {
        LOG.debug("no ds:Signature element present");
        return null;
    }

    KeyInfoKeySelector keyInfoKeySelector = new KeyInfoKeySelector();
    DOMValidateContext valContext = new DOMValidateContext(keyInfoKeySelector, signatureNode);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
    XMLSignature signature;
    try {
        signature = xmlSignatureFactory.unmarshalXMLSignature(valContext);
    } catch (MarshalException e) {
        throw new RuntimeException("XML signature parse error: " + e.getMessage(), e);
    }
    boolean coreValidity;
    try {
        coreValidity = signature.validate(valContext);
    } catch (XMLSignatureException e) {
        throw new RuntimeException("XML signature error: " + e.getMessage(), e);
    }

    // TODO: check what has been signed

    if (coreValidity) {
        LOG.debug("signature valid");
        return keyInfoKeySelector.getCertificate();
    }
    LOG.debug("signature invalid");

    return null;
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

public void validate(RoleDescriptorType md, Document doc, Node root) throws SamlR2SignatureException {
    try {//from ww w  . j a  v a 2 s. c  o m

        // Check for duplicate IDs among XML elements
        NodeList nodes = evaluateXPath(doc, "//*/@ID");
        boolean duplicateIdExists = false;
        List<String> ids = new ArrayList<String>();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (ids.contains(node.getNodeValue())) {
                duplicateIdExists = true;
                logger.error("Duplicated Element ID in XML Document : " + node.getNodeValue());
            }
            ids.add(node.getNodeValue());
        }
        if (duplicateIdExists) {
            throw new SamlR2SignatureException("Duplicate IDs in document ");
        }

        // TODO : Check that the Signature references the root element (the one used by the application)
        // Keep in mind that signature reference might be an XPath expression ?!

        // We know that in SAML, the root element is the element used by the application, we just need to make sure that
        // the root element is the one referred by the signature

        Node rootIdAttr = root.getAttributes().getNamedItem("ID");
        if (rootIdAttr == null)
            throw new SamlR2SignatureException("SAML document does not have an ID ");

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

        // Create a DOM XMLSignatureFactory that will be used to unmarshal the
        // document containing the XMLSignature
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider);

        // Create a DOMValidateContext and specify a KeyValue KeySelector
        // and document context

        // Validate all Signature elements
        boolean rootIdMatched = false;
        for (int k = 0; k < signatureNodes.getLength(); k++) {

            DOMValidateContext valContext = new DOMValidateContext(new RawX509KeySelector(),
                    signatureNodes.item(k));

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

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

            // Check core validation status
            if (!coreValidity) {

                if (logger.isDebugEnabled())
                    logger.debug("Signature failed core validation");

                boolean sv = signature.getSignatureValue().validate(valContext);

                if (logger.isDebugEnabled())
                    logger.debug("signature validation status: " + sv);
                // check the validation status of each Reference (should be only one!)
                Iterator i = signature.getSignedInfo().getReferences().iterator();
                boolean refValid = true;
                for (int j = 0; i.hasNext(); j++) {

                    Reference ref = (Reference) i.next();
                    boolean b = ref.validate(valContext);
                    if (logger.isDebugEnabled())
                        logger.debug("ref[" + j + "] " + ref.getId() + " validity status: " + b);

                    if (!b) {
                        refValid = b;
                        logger.error("Signature failed reference validation " + ref.getId());
                    }

                }
                throw new SamlR2SignatureValidationException(
                        "Signature failed core validation" + (refValid ? " but passed all Reference validations"
                                : " and some/all Reference validation"));
            }

            if (logger.isDebugEnabled())
                logger.debug("Singnature passed Core validation");

            // The Signature must contain only one reference, and it must be the signed top element's ID.
            List<Reference> refs = signature.getSignedInfo().getReferences();
            if (refs.size() != 1) {
                throw new SamlR2SignatureValidationException(
                        "Invalid number of 'Reference' elements in signature : " + refs.size() + " ["
                                + signature.getId() + "]");
            }

            Reference reference = refs.get(0);
            String referenceURI = reference.getURI();

            if (referenceURI == null || !referenceURI.startsWith("#"))
                throw new SamlR2SignatureValidationException(
                        "Signature reference URI format not supported " + referenceURI);

            if (referenceURI.substring(1).equals(rootIdAttr.getNodeValue()))
                rootIdMatched = true;

            Key key = signature.getKeySelectorResult().getKey();
            boolean certValidity = validateCertificate(md, key);
            if (!certValidity) {
                throw new SamlR2SignatureValidationException("Signature failed Certificate validation");
            }

            if (logger.isDebugEnabled())
                logger.debug("Signature passed Certificate validation");

        }

        // Check that any of the Signatures matched the root element ID
        if (!rootIdMatched) {
            logger.error("No Signature element refers to signed element (possible signature wrapping attack)");
            throw new SamlR2SignatureValidationException("No Signature element refers to signed element");
        }

    } catch (MarshalException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}