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

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

Introduction

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

Prototype

String getId();

Source Link

Document

Returns the optional Id attribute of this Reference, which permits this reference to be referenced from elsewhere.

Usage

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

protected QualifyingPropertiesType createXAdESQualifyingProperties(SignatureParameters params,
        String signedInfoId, List<Reference> documentReferences, Document document) {

    // QualifyingProperties
    QualifyingPropertiesType qualifyingProperties = xades13ObjectFactory.createQualifyingPropertiesType();

    SignedPropertiesType signedProperties = xades13ObjectFactory.createSignedPropertiesType();
    qualifyingProperties.setSignedProperties(signedProperties);

    signedProperties.setId(signedInfoId);

    SignedSignaturePropertiesType signedSignatureProperties = xades13ObjectFactory
            .createSignedSignaturePropertiesType();
    signedProperties.setSignedSignatureProperties(signedSignatureProperties);

    // SigningTime
    GregorianCalendar signingTime = new GregorianCalendar(TimeZone.getTimeZone("Z"));
    signingTime.setTime(params.getSigningDate());

    XMLGregorianCalendar xmlGregorianCalendar = getDataFactory().newXMLGregorianCalendar(signingTime);
    xmlGregorianCalendar.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    signedSignatureProperties.setSigningTime(xmlGregorianCalendar);

    X509Certificate signingCertificate = params.getSigningCertificate();
    CertIDType signingCertificateId = getCertID(signingCertificate);
    CertIDListType signingCertificates = xades13ObjectFactory.createCertIDListType();
    signingCertificates.getCert().add(signingCertificateId);
    signedSignatureProperties.setSigningCertificate(signingCertificates);

    // DataObjectProperties
    SignedDataObjectPropertiesType dataObjectProperties = new SignedDataObjectPropertiesType();
    Iterator<Reference> refIt = documentReferences.iterator();
    Iterator<Document> docIt = documentIterator(document);
    while (refIt.hasNext() && docIt.hasNext()) {
        Reference ref = refIt.next();
        Document doc = docIt.next();
        if (ref.getId() != null && doc.getMimeType() != null) {
            DataObjectFormatType dataFormat = new DataObjectFormatType();
            dataFormat.setObjectReference("#" + ref.getId());
            dataFormat.setMimeType(doc.getMimeType().getCode());
            dataObjectProperties.getDataObjectFormat().add(dataFormat);
        }/*ww  w .j  av  a  2 s.  c o m*/
    }
    if (dataObjectProperties.getDataObjectFormat().size() > 0) {
        signedProperties.setSignedDataObjectProperties(dataObjectProperties);
    }

    // SignerRole
    if (params.getClaimedSignerRole() != null) {
        SignerRoleType signerRole = xades13ObjectFactory.createSignerRoleType();
        ClaimedRolesListType claimedRoles = xades13ObjectFactory.createClaimedRolesListType();

        /*
         * Add only one role
         */
        AnyType role = xades13ObjectFactory.createAnyType();
        role.getContent().add(params.getClaimedSignerRole());
        claimedRoles.getClaimedRole().add(role);

        signerRole.setClaimedRoles(claimedRoles);

        signedSignatureProperties.setSignerRole(signerRole);
    }

    return qualifyingProperties;
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMReference.java

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }/*  www.j  a v  a  2s. c  o  m*/

    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.jcp.xml.dsig.internal.dom.DOMXMLSignature.java

public void sign(XMLSignContext signContext) throws MarshalException, XMLSignatureException {
    if (signContext == null) {
        throw new NullPointerException("signContext cannot be null");
    }/*from   w  ww.  ja v  a 2 s. c  o  m*/
    DOMSignContext context = (DOMSignContext) signContext;
    marshal(context.getParent(), context.getNextSibling(), DOMUtils.getSignaturePrefix(context), context);

    // generate references and signature value
    List<Reference> allReferences = new ArrayList<Reference>();

    // traverse the Signature and register all objects with IDs that
    // may contain References
    signatureIdMap = new HashMap<String, XMLStructure>();
    signatureIdMap.put(id, this);
    signatureIdMap.put(si.getId(), si);
    @SuppressWarnings("unchecked")
    List<Reference> refs = si.getReferences();
    for (Reference ref : refs) {
        signatureIdMap.put(ref.getId(), ref);
    }
    for (XMLObject obj : objects) {
        signatureIdMap.put(obj.getId(), obj);
        @SuppressWarnings("unchecked")
        List<XMLStructure> content = obj.getContent();
        for (XMLStructure xs : content) {
            if (xs instanceof Manifest) {
                Manifest man = (Manifest) xs;
                signatureIdMap.put(man.getId(), man);
                @SuppressWarnings("unchecked")
                List<Reference> manRefs = man.getReferences();
                for (Reference ref : manRefs) {
                    allReferences.add(ref);
                    signatureIdMap.put(ref.getId(), ref);
                }
            }
        }
    }
    // always add SignedInfo references after Manifest references so
    // that Manifest reference are digested first
    allReferences.addAll(refs);

    // generate/digest each reference
    for (Reference ref : allReferences) {
        digestReference((DOMReference) ref, signContext);
    }

    // do final sweep to digest any references that were skipped or missed
    for (Reference ref : allReferences) {
        if (((DOMReference) ref).isDigested()) {
            continue;
        }
        ((DOMReference) ref).digest(signContext);
    }

    Key signingKey = null;
    KeySelectorResult ksr = null;
    try {
        ksr = signContext.getKeySelector().select(ki, KeySelector.Purpose.SIGN, si.getSignatureMethod(),
                signContext);
        signingKey = ksr.getKey();
        if (signingKey == null) {
            throw new XMLSignatureException("the keySelector did not " + "find a signing key");
        }
    } catch (KeySelectorException kse) {
        throw new XMLSignatureException("cannot find signing key", kse);
    }

    // calculate signature value
    try {
        byte[] val = ((AbstractDOMSignatureMethod) si.getSignatureMethod()).sign(signingKey, si, signContext);
        ((DOMSignatureValue) sv).setValue(val);
    } catch (InvalidKeyException ike) {
        throw new XMLSignatureException(ike);
    }

    this.localSigElem = sigElem;
    this.ksr = ksr;
}

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 av  a 2  s.  c om

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

From source file:org.jcp.xml.dsig.internal.dom.DOMXMLSignature.java

public void sign(XMLSignContext signContext) throws MarshalException, XMLSignatureException {
    if (signContext == null) {
        throw new NullPointerException("signContext cannot be null");
    }//from   w ww .  j a  v  a 2  s . co  m
    DOMSignContext context = (DOMSignContext) signContext;
    if (context != null) {
        marshal(context.getParent(), context.getNextSibling(), DOMUtils.getSignaturePrefix(context), context);
    }

    // generate references and signature value
    List<Reference> allReferences = new ArrayList<Reference>();

    // traverse the Signature and register all objects with IDs that
    // may contain References
    signatureIdMap = new HashMap<String, XMLStructure>();
    signatureIdMap.put(id, this);
    signatureIdMap.put(si.getId(), si);
    @SuppressWarnings("unchecked")
    List<Reference> refs = si.getReferences();
    for (Reference ref : refs) {
        signatureIdMap.put(ref.getId(), ref);
    }
    for (XMLObject obj : objects) {
        signatureIdMap.put(obj.getId(), obj);
        @SuppressWarnings("unchecked")
        List<XMLStructure> content = obj.getContent();
        for (XMLStructure xs : content) {
            if (xs instanceof Manifest) {
                Manifest man = (Manifest) xs;
                signatureIdMap.put(man.getId(), man);
                @SuppressWarnings("unchecked")
                List<Reference> manRefs = man.getReferences();
                for (Reference ref : manRefs) {
                    allReferences.add(ref);
                    signatureIdMap.put(ref.getId(), ref);
                }
            }
        }
    }
    // always add SignedInfo references after Manifest references so
    // that Manifest reference are digested first
    allReferences.addAll(refs);

    // generate/digest each reference
    for (Reference ref : allReferences) {
        digestReference((DOMReference) ref, signContext);
    }

    // do final sweep to digest any references that were skipped or missed
    for (Reference ref : allReferences) {
        if (((DOMReference) ref).isDigested()) {
            continue;
        }
        ((DOMReference) ref).digest(signContext);
    }

    Key signingKey = null;
    KeySelectorResult ksr = null;
    try {
        ksr = signContext.getKeySelector().select(ki, KeySelector.Purpose.SIGN, si.getSignatureMethod(),
                signContext);
        signingKey = ksr.getKey();
        if (signingKey == null) {
            throw new XMLSignatureException("the keySelector did not " + "find a signing key");
        }
    } catch (KeySelectorException kse) {
        throw new XMLSignatureException("cannot find signing key", kse);
    }

    // calculate signature value
    try {
        byte[] val = ((AbstractDOMSignatureMethod) si.getSignatureMethod()).sign(signingKey, si, signContext);
        ((DOMSignatureValue) sv).setValue(val);
    } catch (InvalidKeyException ike) {
        throw new XMLSignatureException(ike);
    }

    this.localSigElem = sigElem;
    this.ksr = ksr;
}