Example usage for javax.xml.crypto.dsig XMLSignature getSignedInfo

List of usage examples for javax.xml.crypto.dsig XMLSignature getSignedInfo

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig XMLSignature getSignedInfo.

Prototype

SignedInfo getSignedInfo();

Source Link

Document

Returns the signed info of this XMLSignature.

Usage

From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java

@SuppressWarnings("unchecked")
public static String findReferenceUri(XMLSignature xmlSignature, String type) {

    SignedInfo signedInfo = xmlSignature.getSignedInfo();
    List<Reference> references = signedInfo.getReferences();
    for (Reference reference : references) {
        if (type.equals(reference.getType())) {
            return reference.getURI();
        }/*from  w ww.j  a v  a2s  .  c o  m*/
    }

    return null;
}

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
 */// w w  w.  ja  va2s  .  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

/**
 * Obtiene el certificado digital contenido en un nodo XML Sinature (<a
 * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>)
 * /*from ww w  .  jav a 2 s .  co m*/
 * @param signature
 *            el nodo con el tag &lt;Signature&gt;.
 * @return El certificado digital contenido en el &lt;KeyInfo&gt; o
 *         <code>null</code> en caso que el &lt;Signature&gt; no contenga
 *         tal informaci&oacute;n.
 */
@SuppressWarnings("unchecked")
public static X509Certificate getCertificate(XMLSignature signature) {

    String alg = signature.getSignedInfo().getSignatureMethod().getAlgorithm();
    KeyInfo kinf = signature.getKeyInfo();

    // Check for keyinfo
    if (kinf == null) {
        return null;
    }

    PublicKey pKey = null;
    List<X509Certificate> x509 = new ArrayList<X509Certificate>();

    // I look for the public key and the certificates
    for (XMLStructure xst : (List<XMLStructure>) kinf.getContent()) {
        if (xst instanceof KeyValue) {
            PublicKey pk;
            try {
                pk = ((KeyValue) xst).getPublicKey();
                if (algEquals(alg, pk.getAlgorithm()))
                    pKey = pk;
            } catch (KeyException e) {
                // nothing
            }
        }
        if (xst instanceof X509Data) {
            for (Object cont : ((X509Data) xst).getContent())
                if (cont instanceof X509Certificate)
                    x509.add((X509Certificate) cont);
        }
    }

    // return of the certificates that matchs the public key.
    for (X509Certificate cert : x509) {
        if (cert.getPublicKey().equals(pKey)) {
            return cert;
        }
    }

    return null;
}

From source file:com.helger.peppol.httpclient.SMPHttpResponseHandlerSigned.java

private static boolean _checkSignature(@Nonnull @WillClose final InputStream aEntityInputStream)
        throws Exception {
    try {//from  ww w .  j a va  2s  . c o  m
        // Get response from servlet
        final Document aDocument = DOMReader.readXMLDOM(aEntityInputStream);

        // We make sure that the XML is a Signed. If not, we don't have to check
        // any certificates.

        // Find Signature element.
        final NodeList aNodeList = aDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (aNodeList == null || aNodeList.getLength() == 0)
            throw new IllegalArgumentException("Element <Signature> not found in SMP XML response");

        // Create a DOMValidateContext and specify a KeySelector
        // and document context.
        final X509KeySelector aKeySelector = new X509KeySelector();
        final DOMValidateContext aValidateContext = new DOMValidateContext(aKeySelector, aNodeList.item(0));
        final XMLSignatureFactory aSignatureFactory = XMLSignatureFactory.getInstance("DOM");

        // Unmarshal the XMLSignature.
        final XMLSignature aSignature = aSignatureFactory.unmarshalXMLSignature(aValidateContext);

        // Validate the XMLSignature.
        final boolean bCoreValid = aSignature.validate(aValidateContext);
        if (!bCoreValid) {
            // This code block is for debugging purposes only - it has no semantical
            // influence
            s_aLogger.info("Signature failed core validation");
            final boolean bSignatureValueValid = aSignature.getSignatureValue().validate(aValidateContext);
            s_aLogger.info("  Signature value valid: " + bSignatureValueValid);
            if (!bSignatureValueValid) {
                // Check the validation status of each Reference.
                int nIndex = 0;
                final Iterator<?> i = aSignature.getSignedInfo().getReferences().iterator();
                while (i.hasNext()) {
                    final boolean bRefValid = ((Reference) i.next()).validate(aValidateContext);
                    s_aLogger.info("  Reference[" + nIndex + "] validity status: "
                            + (bRefValid ? "valid" : "NOT valid!"));
                    ++nIndex;
                }
            }
        }
        return bCoreValid;
    } finally {
        // Close the input stream
        StreamHelper.close(aEntityInputStream);
    }
}

From source file:be.fedict.eid.dss.document.odf.ODFDSSDocumentService.java

private void checkIntegrity(XMLSignature xmlSignature, byte[] document, byte[] originalDocument)
        throws IOException {
    if (null != originalDocument) {
        throw new IllegalArgumentException("cannot perform original document verifications");
    }//from ww w . j  av  a2 s.  c o  m
    Set<String> dsReferenceUris = new HashSet<String>();
    SignedInfo signedInfo = xmlSignature.getSignedInfo();
    @SuppressWarnings("unchecked")
    List<Reference> references = signedInfo.getReferences();
    for (Reference reference : references) {
        String referenceUri = reference.getURI();
        dsReferenceUris.add(referenceUri);
    }
    ZipInputStream odfZipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;
    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (false == ODFUtil.isToBeSigned(zipEntry)) {
            continue;
        }
        String uri = zipEntry.getName().replaceAll(" ", "%20");
        if (false == dsReferenceUris.contains(uri)) {
            LOG.warn("no ds:Reference for ODF entry: " + zipEntry.getName());
            throw new RuntimeException("no ds:Reference for ODF entry: " + zipEntry.getName());
        }
    }
}

From source file:be.fedict.eid.dss.document.asic.ASiCDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    if (null != originalDocument) {
        throw new IllegalArgumentException("cannot perform original document verifications");
    }//from ww  w  .ja  v a2s.co  m
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ASiCUtil.isSignatureZipEntry(zipEntry)) {
            break;
        }
    }
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    if (null == zipEntry) {
        return signatureInfos;
    }
    XAdESValidation xadesValidation = new XAdESValidation(this.documentContext);
    Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream);
    NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
        Element signatureElement = (Element) signatureNodeList.item(idx);
        xadesValidation.prepareDocument(signatureElement);
        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
        ASiCURIDereferencer dereferencer = new ASiCURIDereferencer(document);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean valid = xmlSignature.validate(domValidateContext);
        if (!valid) {
            continue;
        }

        // check whether all files have been signed properly
        SignedInfo signedInfo = xmlSignature.getSignedInfo();
        @SuppressWarnings("unchecked")
        List<Reference> references = signedInfo.getReferences();
        Set<String> referenceUris = new HashSet<String>();
        for (Reference reference : references) {
            String referenceUri = reference.getURI();
            referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8"));
        }
        zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
        while (null != (zipEntry = zipInputStream.getNextEntry())) {
            if (ASiCUtil.isSignatureZipEntry(zipEntry)) {
                continue;
            }
            if (false == referenceUris.contains(zipEntry.getName())) {
                LOG.warn("no ds:Reference for ASiC entry: " + zipEntry.getName());
                return signatureInfos;
            }
        }

        X509Certificate signer = keySelector.getCertificate();
        SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature,
                signatureElement, signer);
        signatureInfos.add(signatureInfo);
    }
    return signatureInfos;
}

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

private void verifyCoSignatureReference(XMLSignature xmlSignature, Document originalDomDocument)
        throws XMLSecurityException, TransformationException, XMLSignatureException,
        ReferenceNotInitializedException, Base64DecodingException {
    SignedInfo signedInfo = xmlSignature.getSignedInfo();
    @SuppressWarnings("unchecked")
    List<Reference> references = signedInfo.getReferences();
    for (Reference reference : references) {
        LOG.debug("reference type: " + reference.getType());
        if (null != reference.getType()) {
            /*//from   w  w w .  ja  v a2 s . com
             * We skip XAdES and eID identity ds:Reference.
             */
            continue;
        }
        String digestAlgo = reference.getDigestMethod().getAlgorithm();
        LOG.debug("ds:Reference digest algo: " + digestAlgo);
        byte[] digestValue = reference.getDigestValue();

        // xmlsec 1.5 changed the constructor
        org.apache.xml.security.signature.XMLSignature xmldsig = new org.apache.xml.security.signature.XMLSignature(
                originalDomDocument, "",
                org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
                Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS);

        Transforms transforms = new Transforms(originalDomDocument);

        // XPath v1 - slow
        //            XPathContainer xpath = new XPathContainer(originalDomDocument);
        //         xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
        //         xpath.setXPath("not(ancestor-or-self::ds:Signature)");
        //         transforms.addTransform(Transforms.TRANSFORM_XPATH,
        //               xpath.getElementPlusReturns());

        // XPath v2 - fast
        XPath2FilterContainer xpath = XPath2FilterContainer.newInstanceSubtract(originalDomDocument,
                "/descendant::*[name()='ds:Signature']");
        xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
        transforms.addTransform(Transforms.TRANSFORM_XPATH2FILTER, xpath.getElementPlusReturns());

        transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
        xmldsig.addDocument("", transforms, digestAlgo);

        org.apache.xml.security.signature.SignedInfo apacheSignedInfo = xmldsig.getSignedInfo();
        org.apache.xml.security.signature.Reference apacheReference = apacheSignedInfo.item(0);
        apacheReference.generateDigestValue();
        byte[] originalDigestValue = apacheReference.getDigestValue();
        if (false == Arrays.equals(originalDigestValue, digestValue)) {
            throw new RuntimeException("not original document");
        }
        LOG.debug("co-signature ds:Reference checked");
    }
}

From source file:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;//from   ww w  .  j  a  va 2  s  . c  o m
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            break;
        }
    }
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    if (null == zipEntry) {
        return signatureInfos;
    }
    XAdESValidation xadesValidation = new XAdESValidation(this.documentContext);
    Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream);
    NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
        Element signatureElement = (Element) signatureNodeList.item(idx);
        xadesValidation.prepareDocument(signatureElement);

        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
        ZIPURIDereferencer dereferencer = new ZIPURIDereferencer(document);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean valid = xmlSignature.validate(domValidateContext);
        if (!valid) {
            continue;
        }

        // check whether all files have been signed properly
        SignedInfo signedInfo = xmlSignature.getSignedInfo();
        @SuppressWarnings("unchecked")
        List<Reference> references = signedInfo.getReferences();
        Set<String> referenceUris = new HashSet<String>();
        for (Reference reference : references) {
            String referenceUri = reference.getURI();
            referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8"));
        }
        zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
        while (null != (zipEntry = zipInputStream.getNextEntry())) {
            if (ODFUtil.isSignatureFile(zipEntry)) {
                continue;
            }
            if (!referenceUris.contains(zipEntry.getName())) {
                LOG.warn("no ds:Reference for ZIP entry: " + zipEntry.getName());
                return signatureInfos;
            }
        }

        if (null != originalDocument) {
            for (Reference reference : references) {
                if (null != reference.getType()) {
                    /*
                       * We skip XAdES and eID identity ds:Reference.
                       */
                    continue;
                }
                String digestAlgo = reference.getDigestMethod().getAlgorithm();
                LOG.debug("ds:Reference digest algo: " + digestAlgo);
                String referenceUri = reference.getURI();
                LOG.debug("ds:Reference URI: " + referenceUri);
                byte[] digestValue = reference.getDigestValue();

                org.apache.xml.security.signature.XMLSignature xmldsig = new org.apache.xml.security.signature.XMLSignature(
                        documentSignaturesDocument, "",
                        org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
                        Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS);
                xmldsig.addDocument(referenceUri, null, digestAlgo);
                ResourceResolverSpi zipResourceResolver = new ZIPResourceResolver(originalDocument);
                xmldsig.addResourceResolver(zipResourceResolver);
                org.apache.xml.security.signature.SignedInfo apacheSignedInfo = xmldsig.getSignedInfo();
                org.apache.xml.security.signature.Reference apacheReference = apacheSignedInfo.item(0);
                apacheReference.generateDigestValue();
                byte[] originalDigestValue = apacheReference.getDigestValue();
                if (!Arrays.equals(originalDigestValue, digestValue)) {
                    throw new RuntimeException("not original document");
                }
            }
            /*
             * So we already checked whether no files were changed, and that
             * no files were added compared to the original document. Still
             * have to check whether no files were removed.
             */
            ZipInputStream originalZipInputStream = new ZipInputStream(
                    new ByteArrayInputStream(originalDocument));
            ZipEntry originalZipEntry;
            Set<String> referencedEntryNames = new HashSet<String>();
            for (Reference reference : references) {
                if (null != reference.getType()) {
                    continue;
                }
                referencedEntryNames.add(reference.getURI());
            }
            while (null != (originalZipEntry = originalZipInputStream.getNextEntry())) {
                if (ODFUtil.isSignatureFile(originalZipEntry)) {
                    continue;
                }
                if (!referencedEntryNames.contains(originalZipEntry.getName())) {
                    LOG.warn("missing ds:Reference for ZIP entry: " + originalZipEntry.getName());
                    throw new RuntimeException(
                            "missing ds:Reference for ZIP entry: " + originalZipEntry.getName());
                }
            }
        }

        X509Certificate signer = keySelector.getCertificate();
        SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature,
                signatureElement, signer);
        signatureInfos.add(signatureInfo);
    }
    return signatureInfos;
}

From source file:com.vmware.identity.sts.ws.SignatureValidator.java

/**
 * Validate the canonicalization method of the signature.
 * @param xmlSignature the XMLSignature to validate the canonicalization method of.
 * @throws XMLSignatureException when validation fails.
 *//*ww w  . jav a 2s.  co  m*/
private void validateCanonicalizationMethod(XMLSignature xmlSignature) throws XMLSignatureException {
    assert xmlSignature != null;

    // Exclusive canonicalization without comments (xml-exc-c14n) must be used prior to signature generation.
    if (!CanonicalizationMethod.EXCLUSIVE
            .equals(xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm())) {
        throw new XMLSignatureException(String.format("Canonicalization algorithm '%s' is not supported.",
                xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm()));
    }
}

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

private boolean verify_signature(final Signature signature2) {
    try {//from   w  w w  .j  a  va 2 s .  com
        signature2.getBytes();
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);
        DocumentBuilder builder = fac.newDocumentBuilder();
        final Document doc = builder.parse(new ByteArrayInputStream(signature2.getBytes()));
        //System.err.println(new String(signature2.getBytes()));
        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        DOMValidateContext valContext = new DOMValidateContext(
                noekkelpar.getSertifikat().getX509Certificate().getPublicKey(), nl.item(0));
        valContext.setURIDereferencer(new URIDereferencer() {
            @Override
            public Data dereference(final URIReference uriReference, final XMLCryptoContext context)
                    throws URIReferenceException {
                //System.out.println("$$$$ " + uriReference.getURI());
                for (AsicEAttachable file : files) {
                    if (file.getFileName().equals(uriReference.getURI().toString())) {
                        return new OctetStreamData(new ByteArrayInputStream(file.getBytes()));
                    }
                }
                uriReference.getURI().toString().replace("#", "");
                Node element = doc.getElementsByTagName("SignedProperties").item(0);
                return new DOMSubTreeData(element, false);

            }
        });
        XMLSignatureFactory fact = XMLSignatureFactory.getInstance("DOM");
        XMLSignature signature = fact.unmarshalXMLSignature(valContext);
        boolean coreValidity = signature.validate(valContext);
        if (coreValidity == false) {
            System.err.println("Signature failed core validation");
            boolean sv = signature.getSignatureValue().validate(valContext);
            System.out.println("signature validation status: " + sv);
            if (sv == false) {
                // Check the validation status of each Reference.
                Iterator i = signature.getSignedInfo().getReferences().iterator();
                for (int j = 0; i.hasNext(); j++) {
                    boolean refValid = ((javax.xml.crypto.dsig.Reference) i.next()).validate(valContext);
                    System.out.println("ref[" + j + "] validity status: " + refValid);
                }
            }
        }
        return coreValidity;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return false;
    }
}