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

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

Introduction

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

Prototype

DigestMethod getDigestMethod();

Source Link

Document

Returns the digest method of this Reference.

Usage

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   ww w.j  a 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   w  ww . j  ava 2 s  .  co 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:org.apache.jcp.xml.dsig.internal.dom.DOMReference.java

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }// w w w . j  ava2 s. com

    if (!(o instanceof Reference)) {
        return false;
    }
    Reference oref = (Reference) o;

    boolean idsEqual = (id == null ? oref.getId() == null : id.equals(oref.getId()));
    boolean urisEqual = (uri == null ? oref.getURI() == null : uri.equals(oref.getURI()));
    boolean typesEqual = (type == null ? oref.getType() == null : type.equals(oref.getType()));
    boolean digestValuesEqual = Arrays.equals(digestValue, oref.getDigestValue());

    return digestMethod.equals(oref.getDigestMethod()) && idsEqual && urisEqual && typesEqual
            && allTransforms.equals(oref.getTransforms()) && digestValuesEqual;
}

From source file:org.apache.ws.security.components.crypto.AlgorithmSuiteValidator.java

/**
 * Check the Signature Algorithms//from w ww .j ava  2s.  c o  m
 */
public void checkSignatureAlgorithms(XMLSignature xmlSignature) throws WSSecurityException {
    // Signature Algorithm
    String signatureMethod = xmlSignature.getSignedInfo().getSignatureMethod().getAlgorithm();
    checkSignatureMethod(signatureMethod);

    // C14n Algorithm
    String c14nMethod = xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm();
    checkC14nAlgorithm(c14nMethod);

    for (Object refObject : xmlSignature.getSignedInfo().getReferences()) {
        Reference reference = (Reference) refObject;
        // Digest Algorithm
        String digestMethod = reference.getDigestMethod().getAlgorithm();
        Set<String> allowedDigestAlgorithms = algorithmSuite.getDigestAlgorithms();
        if (!allowedDigestAlgorithms.isEmpty() && !allowedDigestAlgorithms.contains(digestMethod)) {
            LOG.debug("DigestMethod " + digestMethod + " does not match required value");
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY);
        }

        // Transform Algorithms
        for (int i = 0; i < reference.getTransforms().size(); i++) {
            Transform transform = (Transform) reference.getTransforms().get(i);
            String algorithm = transform.getAlgorithm();
            Set<String> allowedTransformAlgorithms = algorithmSuite.getTransformAlgorithms();
            if (!allowedTransformAlgorithms.isEmpty() && !allowedTransformAlgorithms.contains(algorithm)) {
                LOG.debug("Transform method " + algorithm + " does not match required value");
                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY);
            }
        }
    }
}