Example usage for javax.xml.crypto.dom DOMStructure DOMStructure

List of usage examples for javax.xml.crypto.dom DOMStructure DOMStructure

Introduction

In this page you can find the example usage for javax.xml.crypto.dom DOMStructure DOMStructure.

Prototype

public DOMStructure(Node node) 

Source Link

Document

Creates a DOMStructure containing the specified node.

Usage

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

@Override
public List<AdvancedSignature> getCounterSignatures() {
    // see ETSI TS 101 903 V1.4.2 (2010-12) pp. 38/39/40

    try {/*w w  w.j av a 2 s . c  o  m*/
        NodeList counterSigs = XMLUtils.getNodeList(signatureElement,
                "./ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties"
                        + "/xades:CounterSignature");
        if (counterSigs == null) {
            return null;
        }

        List<AdvancedSignature> xadesList = new ArrayList<AdvancedSignature>();

        for (int i = 0; i < counterSigs.getLength(); i++) {
            Element counterSigEl = (Element) counterSigs.item(i);
            Element signatureEl = XMLUtils.getElement(counterSigEl, "./ds:Signature");

            // Verify that the element is a proper signature by trying to build a XAdESSignature out of it
            XAdESSignature xCounterSig = new XAdESSignature(signatureEl);

            // Verify that there is a ds:Reference element with a Type set to: http://uri.etsi.org/01903#CountersignedSignature
            // (as per the XAdES spec)
            XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
            XMLSignature signature = factory.unmarshalXMLSignature(new DOMStructure(signatureEl));

            LOG.info("Verifying countersignature References");
            for (Object refobj : signature.getSignedInfo().getReferences()) {
                Reference ref = (Reference) refobj;
                if (ref.getType() != null
                        && ref.getType().equals("http://uri.etsi.org/01903#CountersignedSignature")) {
                    // Ok, this seems to be a countersignature

                    // Verify that the digest is that of the signature value
                    if (ref.validate(new DOMValidateContext(xCounterSig.getSigningCertificate().getPublicKey(),
                            XMLUtils.getElement(signatureElement, "./ds:SignatureValue")))) {

                        LOG.info("Reference verification succeeded, adding countersignature");
                        xadesList.add(xCounterSig);
                    } else {
                        LOG.warning(
                                "Skipping countersignature because the Reference doesn't contain a hash of the embedding SignatureValue");
                    }

                    break;
                }
            }
        }

        return xadesList;
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING);
    } catch (MarshalException e) {
        throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING);
    } catch (XMLSignatureException e) {
        throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING);
    }

}

From source file:it.cnr.icar.eric.common.security.wss4j.WSS4JSignatureSAML.java

/**
 * Initialize a WSSec SAML Signature./*from   w  ww . j a v  a2  s .com*/
 * 
 * The method sets up and initializes a WSSec SAML Signature structure after
 * the relevant information was set. After setup of the references to
 * elements to sign may be added. After all references are added they can be
 * signed.
 * 
 * This method does not add the Signature element to the security header.
 * See <code>prependSignatureElementToHeader()</code> method.
 * 
 * @param doc
 *            The SOAP envelope as <code>Document</code>
 * @param uCrypto
 *            The user's Crypto instance
 * @param assertion
 *            the complete SAML assertion
 * @param iCrypto
 *            An instance of the Crypto API to handle keystore SAML token
 *            issuer and to generate certificates
 * @param iKeyName
 *            Private key to use in case of "sender-Vouches"
 * @param iKeyPW
 *            Password for issuer private key
 * @param secHeader
 *            The Security header
 * @throws WSSecurityException
 */
public void prepare(Document doc, Crypto uCrypto, AssertionWrapper assertion, Crypto iCrypto, String iKeyName,
        String iKeyPW, WSSecHeader secHeader) throws WSSecurityException {

    if (doDebug) {
        log.debug("Beginning ST signing...");
    }

    userCrypto = uCrypto;
    issuerCrypto = iCrypto;
    document = doc;
    issuerKeyName = iKeyName;
    issuerKeyPW = iKeyPW;

    samlToken = assertion.toDOM(doc);

    //
    // Get some information about the SAML token content. This controls how
    // to deal with the whole stuff. First get the Authentication statement
    // (includes Subject), then get the _first_ confirmation method only
    // thats if "senderVouches" is true.
    //
    String confirmMethod = null;
    List<String> methods = assertion.getConfirmationMethods();
    if (methods != null && methods.size() > 0) {
        confirmMethod = methods.get(0);
    }
    if (OpenSAMLUtil.isMethodSenderVouches(confirmMethod)) {
        senderVouches = true;
    }
    //
    // Gather some info about the document to process and store it for
    // retrieval
    //
    wsDocInfo = new WSDocInfo(doc);

    X509Certificate[] certs = null;
    PublicKey publicKey = null;

    if (senderVouches) {
        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
        cryptoType.setAlias(issuerKeyName);
        certs = issuerCrypto.getX509Certificates(cryptoType);
        wsDocInfo.setCrypto(issuerCrypto);
    }
    //
    // in case of key holder: - get the user's certificate that _must_ be
    // included in the SAML token. To ensure the cert integrity the SAML
    // token must be signed (by the issuer).
    //
    else {
        if (userCrypto == null || !assertion.isSigned()) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity",
                    new Object[] { "for SAML Signature (Key Holder)" });
        }
        if (secretKey == null) {
            RequestData data = new RequestData();
            data.setSigCrypto(userCrypto);
            data.setWssConfig(getWsConfig());
            SAMLKeyInfo samlKeyInfo = SAMLUtil.getCredentialFromSubject(assertion, data, wsDocInfo,
                    getWsConfig().isWsiBSPCompliant());
            publicKey = samlKeyInfo.getPublicKey();
            certs = samlKeyInfo.getCerts();
            wsDocInfo.setCrypto(userCrypto);
        }
    }
    if ((certs == null || certs.length == 0 || certs[0] == null) && publicKey == null && secretKey == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound",
                new Object[] { "SAML signature" });
    }

    if (sigAlgo == null) {
        PublicKey key = null;
        if (certs != null && certs[0] != null) {
            key = certs[0].getPublicKey();
        } else if (publicKey != null) {
            key = publicKey;
        }

        String pubKeyAlgo = key.getAlgorithm();
        log.debug("automatic sig algo detection: " + pubKeyAlgo);
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            sigAlgo = WSConstants.DSA;
        } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) {
            sigAlgo = WSConstants.RSA;
        } else {
            throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm",
                    new Object[] { pubKeyAlgo });
        }
    }
    sig = null;

    try {
        C14NMethodParameterSpec c14nSpec = null;
        if (getWsConfig().isWsiBSPCompliant() && canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) {
            List<String> prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false);
            c14nSpec = new ExcC14NParameterSpec(prefixes);
        }

        c14nMethod = signatureFactory.newCanonicalizationMethod(canonAlgo, c14nSpec);
    } catch (Exception ex) {
        log.error("", ex);
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
    }

    keyInfoUri = getWsConfig().getIdAllocator().createSecureId("KeyId-", keyInfo);
    secRef = new SecurityTokenReference(doc);
    strUri = getWsConfig().getIdAllocator().createSecureId("STRId-", secRef);
    secRef.setID(strUri);

    if (certs != null && certs.length != 0) {

        // __MOD__ 2012-01-15

        if (certUri == null)
            certUri = getWsConfig().getIdAllocator().createSecureId("CertId-", certs[0]);
    }

    //
    // If the sender vouches, then we must sign the SAML token _and_ at
    // least one part of the message (usually the SOAP body). To do so we
    // need to - put in a reference to the SAML token. Thus we create a STR
    // and insert it into the wsse:Security header - set a reference of the
    // created STR to the signature and use STR Transform during the
    // signature
    //
    try {
        if (senderVouches) {
            secRefSaml = new SecurityTokenReference(doc);
            secRefID = getWsConfig().getIdAllocator().createSecureId("STRSAMLId-", secRefSaml);
            secRefSaml.setID(secRefID);

            if (useDirectReferenceToAssertion) {
                Reference ref = new Reference(doc);
                ref.setURI("#" + assertion.getId());
                if (assertion.getSaml1() != null) {
                    ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
                    secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                } else if (assertion.getSaml2() != null) {
                    secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
                }
                secRefSaml.setReference(ref);
            } else {
                Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
                String valueType = null;
                if (assertion.getSaml1() != null) {
                    valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE;
                    secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                } else if (assertion.getSaml2() != null) {
                    valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE;
                    secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
                }
                keyId.setAttributeNS(null, "ValueType", valueType);
                keyId.appendChild(doc.createTextNode(assertion.getId()));
                Element elem = secRefSaml.getElement();
                elem.appendChild(keyId);
            }
            wsDocInfo.addTokenElement(secRefSaml.getElement(), false);
        }
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
    }

    if (senderVouches) {
        switch (keyIdentifierType) {
        case WSConstants.BST_DIRECT_REFERENCE:
            Reference ref = new Reference(doc);
            ref.setURI("#" + certUri);
            bstToken = new X509Security(doc);
            ((X509Security) bstToken).setX509Certificate(certs[0]);
            bstToken.setID(certUri);
            wsDocInfo.addTokenElement(bstToken.getElement(), false);
            ref.setValueType(bstToken.getValueType());
            secRef.setReference(ref);
            break;

        case WSConstants.X509_KEY_IDENTIFIER:
            secRef.setKeyIdentifier(certs[0]);
            break;

        case WSConstants.SKI_KEY_IDENTIFIER:
            secRef.setKeyIdentifierSKI(certs[0], iCrypto != null ? iCrypto : uCrypto);
            break;

        case WSConstants.THUMBPRINT_IDENTIFIER:
            secRef.setKeyIdentifierThumb(certs[0]);
            break;

        case WSConstants.ISSUER_SERIAL:
            final String issuer = certs[0].getIssuerDN().getName();
            final java.math.BigInteger serialNumber = certs[0].getSerialNumber();
            final DOMX509IssuerSerial domIssuerSerial = new DOMX509IssuerSerial(document, issuer, serialNumber);
            final DOMX509Data domX509Data = new DOMX509Data(document, domIssuerSerial);
            secRef.setX509Data(domX509Data);
            break;

        default:
            throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId", new Object[] {});
        }
    } else if (useDirectReferenceToAssertion) {
        Reference ref = new Reference(doc);
        ref.setURI("#" + assertion.getId());
        if (assertion.getSaml1() != null) {
            ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
            secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
        } else if (assertion.getSaml2() != null) {
            secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
        }
        secRef.setReference(ref);
    } else {
        Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
        String valueType = null;
        if (assertion.getSaml1() != null) {
            valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE;
            secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
        } else if (assertion.getSaml2() != null) {
            valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE;
            secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
        }
        keyId.setAttributeNS(null, "ValueType", valueType);
        keyId.appendChild(doc.createTextNode(assertion.getId()));
        Element elem = secRef.getElement();
        elem.appendChild(keyId);
    }
    XMLStructure structure = new DOMStructure(secRef.getElement());
    wsDocInfo.addTokenElement(secRef.getElement(), false);

    keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(structure), keyInfoUri);

    wsDocInfo.addTokenElement(samlToken, false);
}

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

private DOMXMLSignature createEnveloping(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    List<XMLObject> objects = new ArrayList<XMLObject>();
    List<Reference> references = new ArrayList<Reference>();

    byte[] b64data = Base64.encode(IOUtils.toByteArray(inside.openStream()));

    List<Transform> transforms = new ArrayList<Transform>();
    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");
    Transform exclusiveTransform = fac.newTransform(CanonicalizationMethod.BASE64,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);/*  w  ww .  j a v  a 2  s. co m*/

    /* The first reference concern the whole document */
    Reference reference = fac.newReference("#signed-data-" + computeDeterministicId(params), digestMethod,
            transforms, null, "signed-data-ref");
    references.add(reference);

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.PLAIN);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);

    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    Element dsObject = doc.createElementNS(XMLSignature.XMLNS, "Object");
    dsObject.setAttribute("Id", "signed-data-" + computeDeterministicId(params));
    dsObject.setTextContent(new String(b64data));
    doc.getDocumentElement().appendChild(dsObject);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");
    signContext.setIdAttributeNS(dsObject, null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private void addSignatureInfo(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    List<XMLStructure> objectContent = new LinkedList<XMLStructure>();

    Element signatureInfoElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureInfoV1");
    signatureInfoElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", OFFICE_DIGSIG_NS);

    Element setupIDElement = document.createElementNS(OFFICE_DIGSIG_NS, "SetupID");

    signatureInfoElement.appendChild(setupIDElement);

    Element signatureTextElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureText");

    signatureInfoElement.appendChild(signatureTextElement);

    Element signatureImageElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureImage");

    signatureInfoElement.appendChild(signatureImageElement);

    Element signatureCommentsElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureComments");

    signatureInfoElement.appendChild(signatureCommentsElement);

    Element windowsVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "WindowsVersion");
    windowsVersionElement.setTextContent("6.1");
    signatureInfoElement.appendChild(windowsVersionElement);

    Element officeVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "OfficeVersion");
    officeVersionElement.setTextContent("15.0");
    signatureInfoElement.appendChild(officeVersionElement);

    Element applicationVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "ApplicationVersion");
    applicationVersionElement.setTextContent("15.0");
    signatureInfoElement.appendChild(applicationVersionElement);

    Element monitorsElement = document.createElementNS(OFFICE_DIGSIG_NS, "Monitors");
    monitorsElement.setTextContent("1");
    signatureInfoElement.appendChild(monitorsElement);

    Element horizontalResolutionElement = document.createElementNS(OFFICE_DIGSIG_NS, "HorizontalResolution");
    horizontalResolutionElement.setTextContent("1366");
    signatureInfoElement.appendChild(horizontalResolutionElement);

    Element verticalResolutionElement = document.createElementNS(OFFICE_DIGSIG_NS, "VerticalResolution");
    verticalResolutionElement.setTextContent("768");
    signatureInfoElement.appendChild(verticalResolutionElement);

    Element colorDepthElement = document.createElementNS(OFFICE_DIGSIG_NS, "ColorDepth");
    colorDepthElement.setTextContent("32");
    signatureInfoElement.appendChild(colorDepthElement);

    Element signatureProviderIdElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureProviderId");
    signatureProviderIdElement.setTextContent("{00000000-0000-0000-0000-000000000000}");
    signatureInfoElement.appendChild(signatureProviderIdElement);

    Element signatureProviderUrlElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureProviderUrl");
    signatureInfoElement.appendChild(signatureProviderUrlElement);

    Element signatureProviderDetailsElement = document.createElementNS(OFFICE_DIGSIG_NS,
            "SignatureProviderDetails");
    signatureProviderDetailsElement.setTextContent("9");
    signatureInfoElement.appendChild(signatureProviderDetailsElement);

    Element manifestHashAlgorithmElement = document.createElementNS(OFFICE_DIGSIG_NS, "ManifestHashAlgorithm");
    manifestHashAlgorithmElement.setTextContent("http://www.w3.org/2000/09/xmldsig#sha1");
    signatureInfoElement.appendChild(manifestHashAlgorithmElement);

    Element signatureTypeElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureType");
    signatureTypeElement.setTextContent("1");
    signatureInfoElement.appendChild(signatureTypeElement);

    List<XMLStructure> signatureInfoContent = new LinkedList<XMLStructure>();
    signatureInfoContent.add(new DOMStructure(signatureInfoElement));
    SignatureProperty signatureInfoSignatureProperty = signatureFactory
            .newSignatureProperty(signatureInfoContent, "#" + signatureId, "idOfficeV1Details");

    List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>();
    signaturePropertyContent.add(signatureInfoSignatureProperty);
    SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent,
            null);// w  w w  .  j  a  v a  2 s  .c o  m
    objectContent.add(signatureProperties);

    String objectId = "idOfficeObject";
    objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));

    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null,
            "http://www.w3.org/2000/09/xmldsig#Object", null);
    references.add(reference);
}

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

private DOMXMLSignature createDetached(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, final Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    // Create references
    List<Reference> references = new ArrayList<Reference>();
    addReferences(documentIterator(inside), references, digestMethod, fac);
    // Create repository
    signContext.setURIDereferencer(new NameBasedDocumentRepository(inside, fac));

    List<XMLObject> objects = new ArrayList<XMLObject>();

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, references, inside);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);//from ww w.  ja va2  s  .c  om

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

@Override
public byte[] getArchiveTimestampData(int index, Document originalData) throws IOException {

    try {/*from   w w w  .  j  av  a2  s  . com*/
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        XMLStructure s = new DOMStructure(signatureElement);
        XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
        DOMXMLSignature signature = (DOMXMLSignature) factory.unmarshalXMLSignature(s);

        DOMSignContext signContext = new DOMSignContext(new SpecialPrivateKey(), signatureElement);
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        signContext.setProperty("javax.xml.crypto.dsig.cacheReference", true);
        signContext.setURIDereferencer(new OneExternalFileURIDereferencer("detached-file", originalData));

        // TODO naramsda: check ! Don't let met publish that without further test !!
        // DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // dbf.setNamespaceAware(true);
        // org.w3c.dom.Document xmlDoc = dbf.newDocumentBuilder().newDocument();
        // signature.marshal(xmlDoc.createElement("test"), "ds", signContext);

        for (Object o : signature.getSignedInfo().getReferences()) {
            DOMReference r = (DOMReference) o;
            InputStream data = r.getDigestInputStream();
            if (data != null) {
                IOUtils.copy(data, buffer);
            }
        }

        List<Node> timeStampNodesXadesA = new LinkedList<Node>();

        Element signedInfo = XMLUtils.getElement(signatureElement, "./ds:SignedInfo");
        timeStampNodesXadesA.add(signedInfo);

        Element signatureValue = XMLUtils.getElement(signatureElement, "./ds:SignatureValue");
        timeStampNodesXadesA.add(signatureValue);

        Element keyInfo = XMLUtils.getElement(signatureElement, "./ds:KeyInfo");
        timeStampNodesXadesA.add(keyInfo);

        Element unsignedSignaturePropertiesNode = getUnsignedSignatureProperties(signatureElement);

        NodeList unsignedProperties = unsignedSignaturePropertiesNode.getChildNodes();
        int count = 0;
        for (int i = 0; i < unsignedProperties.getLength(); i++) {
            if (unsignedProperties.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element unsignedProperty = (Element) unsignedProperties.item(i);
                if ("ArchiveTimeStamp".equals(unsignedProperty.getLocalName())) {
                    if (count == index) {
                        LOG.info("We only need data up to ArchiveTimeStamp index " + index);
                        break;
                    }
                    count++;
                }
                timeStampNodesXadesA.add(unsignedProperty);
            }
        }

        buffer.write(getC14nValue(timeStampNodesXadesA));

        return buffer.toByteArray();
        //        } catch (ParserConfigurationException e) {
        //            throw new IOException("Error when computing the archive data", e);
    } catch (MarshalException e) {
        throw new IOException("Error when computing the archive data", e);
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.ARCHIVE_TIMESTAMP_DATA_ENCODING);
    }
}

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

public void addXadesBes(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        X509Certificate signingCertificate, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("preSign");

    // QualifyingProperties
    QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType();
    qualifyingProperties.setTarget("#" + signatureId);

    // SignedProperties
    SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType();
    String signedPropertiesId = signatureId + "-xades";
    signedProperties.setId(signedPropertiesId);
    qualifyingProperties.setSignedProperties(signedProperties);

    // SignedSignatureProperties
    SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory
            .createSignedSignaturePropertiesType();
    signedProperties.setSignedSignatureProperties(signedSignatureProperties);

    // SigningTime
    GregorianCalendar signingTime = new GregorianCalendar();
    signingTime.setTimeZone(TimeZone.getTimeZone("Z"));
    XMLGregorianCalendar xmlSigningTime = this.datatypeFactory.newXMLGregorianCalendar(signingTime);
    xmlSigningTime.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    signedSignatureProperties.setSigningTime(xmlSigningTime);

    // SigningCertificate
    CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType();
    CertIDType signingCertificateId = this.xadesObjectFactory.createCertIDType();

    X509IssuerSerialType issuerSerial = this.xmldsigObjectFactory.createX509IssuerSerialType();
    issuerSerial.setX509IssuerName(signingCertificate.getIssuerX500Principal().toString());
    issuerSerial.setX509SerialNumber(signingCertificate.getSerialNumber());
    signingCertificateId.setIssuerSerial(issuerSerial);

    DigestAlgAndValueType certDigest = this.xadesObjectFactory.createDigestAlgAndValueType();
    DigestMethodType jaxbDigestMethod = this.xmldsigObjectFactory.createDigestMethodType();
    jaxbDigestMethod.setAlgorithm(DigestMethod.SHA256);
    certDigest.setDigestMethod(jaxbDigestMethod);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digestValue;
    try {/*  ww  w . j  av a  2  s.  co m*/
        digestValue = messageDigest.digest(signingCertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    certDigest.setDigestValue(digestValue);
    signingCertificateId.setCertDigest(certDigest);

    signingCertificates.getCert().add(signingCertificateId);
    signedSignatureProperties.setSigningCertificate(signingCertificates);

    // marshall XAdES QualifyingProperties
    Node qualifyingPropertiesNode = marshallQualifyingProperties(document, qualifyingProperties);

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(qualifyingPropertiesNode));
    XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    // add XAdES ds:Reference
    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null);
    List<Transform> transforms = new LinkedList<Transform>();
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);
    Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms,
            XADES_TYPE, null);
    references.add(reference);
}

From source file:eu.europa.ec.markt.dss.validation102853.xades.XAdESSignature.java

@Override
public List<AdvancedSignature> getCounterSignatures() {

    // see ETSI TS 101 903 V1.4.2 (2010-12) pp. 38/39/40

    try {// w  ww .j a v a  2s.  c  o m
        NodeList counterSigs = DSSXMLUtils.getNodeList(signatureElement, XPATH_COUNTER_SIGNATURE);
        if (counterSigs == null) {
            return null;
        }

        List<AdvancedSignature> xadesList = new ArrayList<AdvancedSignature>();

        for (int i = 0; i < counterSigs.getLength(); i++) {

            Element counterSigEl = (Element) counterSigs.item(i);
            Element signatureEl = DSSXMLUtils.getElement(counterSigEl, XPATH_SIGNATURE);

            // Verify that the element is a proper signature by trying to build a XAdESSignature out of it
            XAdESSignature xCounterSig = new XAdESSignature(signatureEl, certPool);

            /*
             * Verify that there is a ds:Reference element with a Type set to:
             * http://uri.etsi.org/01903#CountersignedSignature (as per the XAdES spec)
             */
            XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
            javax.xml.crypto.dsig.XMLSignature signature = factory
                    .unmarshalXMLSignature(new DOMStructure(signatureEl));

            LOG.info("Verifying countersignature References");
            for (Object refobj : signature.getSignedInfo().getReferences()) {

                Reference ref = (Reference) refobj;
                if (ref.getType() != null && ref.getType().equals(XADES_COUNTERSIGNED_SIGNATURE)) {

                    // Ok, this seems to be a CounterSignature
                    // Verify that the digest is that of the signature value
                    CertificateToken certToken = xCounterSig.getSigningCertificate().getCertToken();
                    PublicKey publicKey = certToken.getCertificate().getPublicKey();
                    if (ref.validate(new DOMValidateContext(publicKey,
                            DSSXMLUtils.getElement(signatureElement, XPATH_SIGNATURE_VALUE)))) {

                        LOG.info("Reference verification succeeded, adding countersignature");
                        xadesList.add(xCounterSig);
                    } else {

                        LOG.warning(
                                "Skipping countersignature because the Reference doesn't contain a hash of the embedding SignatureValue");
                    }
                    break;
                }
            }
        }
        return xadesList;
    } catch (MarshalException e) {

        throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING, e);
    } catch (XMLSignatureException e) {

        throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING, e);
    }
}

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

@Override
public Output get(Input input) throws Exception { //NOPMD

    XmlSignatureProperties.Output result = new Output();

    if (!isAddSignedSignatureProperties() && !isAddSignedDataObjectPropeties()) {
        LOG.debug(/*from ww  w  . ja  v  a2  s  . com*/
                "XAdES signature properties are empty. Therefore no XAdES element will be added to the signature.");
        return result;
    }
    String signedPropertiesId = "_" + UUID.randomUUID().toString();
    Reference ref = input.getSignatureFactory().newReference("#" + signedPropertiesId,
            input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null),
            Collections.emptyList(), "http://uri.etsi.org/01903#SignedProperties", null);

    Node parent = input.getParent();
    Document doc;
    if (Node.DOCUMENT_NODE == parent.getNodeType()) {
        doc = (Document) parent; // enveloping
    } else {
        doc = parent.getOwnerDocument(); // enveloped
    }

    Element qualifyingProperties = createElement("QualifyingProperties", doc, input);
    setIdAttributeFromHeader(XmlSignatureConstants.HEADER_XADES_QUALIFYING_PROPERTIES_ID, qualifyingProperties,
            input);
    String signatureId = input.getSignatureId();
    if (signatureId == null || signatureId.isEmpty()) {
        LOG.debug("No signature Id configured. Therefore a value is generated.");
        // generate one
        signatureId = "_" + UUID.randomUUID().toString();
        // and set to output
        result.setSignatureId(signatureId);
    }
    setAttribute(qualifyingProperties, "Target", "#" + signatureId);
    Element signedProperties = createElement("SignedProperties", doc, input);
    qualifyingProperties.appendChild(signedProperties);
    setAttribute(signedProperties, "Id", signedPropertiesId);
    signedProperties.setIdAttribute("Id", true);
    addSignedSignatureProperties(doc, signedProperties, input);
    String contentReferenceId = addSignedDataObjectProperties(doc, signedProperties, input);
    result.setContentReferenceId(contentReferenceId);
    DOMStructure structure = new DOMStructure(qualifyingProperties);

    XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(structure),
            null, null, null);

    result.setReferences(Collections.singletonList(ref));
    result.setObjects(Collections.singletonList(propertiesObject));

    return result;
}

From source file:org.apache.ws.security.message.WSSecSignatureBase.java

/**
 * This method adds references to the Signature.
 * /*from  w w  w .  jav  a 2 s.  c om*/
 * @param doc The parent document
 * @param references The list of references to sign
 * @param wsDocInfo The WSDocInfo object to store protection elements in
 * @param signatureFactory The XMLSignature object
 * @param secHeader The Security Header
 * @param wssConfig The WSSConfig
 * @param digestAlgo The digest algorithm to use
 * @throws WSSecurityException
 */
public List<javax.xml.crypto.dsig.Reference> addReferencesToSign(Document doc,
        List<WSEncryptionPart> references, WSDocInfo wsDocInfo, XMLSignatureFactory signatureFactory,
        WSSecHeader secHeader, WSSConfig wssConfig, String digestAlgo) throws WSSecurityException {
    DigestMethod digestMethod;
    try {
        digestMethod = signatureFactory.newDigestMethod(digestAlgo, null);
    } catch (Exception ex) {
        log.error("", ex);
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
    }

    List<javax.xml.crypto.dsig.Reference> referenceList = new ArrayList<javax.xml.crypto.dsig.Reference>();

    for (WSEncryptionPart encPart : references) {
        String idToSign = encPart.getId();
        String elemName = encPart.getName();
        Element element = encPart.getElement();

        //
        // Set up the elements to sign. There is one reserved element
        // names: "STRTransform": Setup the ds:Reference to use STR Transform
        //
        try {
            if (idToSign != null) {
                Transform transform = null;
                if ("STRTransform".equals(elemName)) {
                    Element ctx = createSTRParameter(doc);

                    XMLStructure structure = new DOMStructure(ctx);
                    transform = signatureFactory.newTransform(STRTransform.TRANSFORM_URI, structure);
                } else {
                    TransformParameterSpec transformSpec = null;
                    if (element == null) {
                        if (callbackLookup == null) {
                            callbackLookup = new DOMCallbackLookup(doc);
                        }
                        element = callbackLookup.getElement(idToSign, null, false);
                    }
                    if (wssConfig.isWsiBSPCompliant()) {
                        List<String> prefixes = getInclusivePrefixes(element);
                        transformSpec = new ExcC14NParameterSpec(prefixes);
                    }
                    transform = signatureFactory.newTransform(WSConstants.C14N_EXCL_OMIT_COMMENTS,
                            transformSpec);
                }
                if (element != null) {
                    wsDocInfo.addTokenElement(element, false);
                }
                javax.xml.crypto.dsig.Reference reference = signatureFactory.newReference("#" + idToSign,
                        digestMethod, Collections.singletonList(transform), null, null);
                referenceList.add(reference);
            } else {
                String nmSpace = encPart.getNamespace();
                List<Element> elementsToSign = null;
                if (element != null) {
                    elementsToSign = Collections.singletonList(element);
                } else {
                    if (callbackLookup == null) {
                        callbackLookup = new DOMCallbackLookup(doc);
                    }
                    elementsToSign = WSSecurityUtil.findElements(encPart, callbackLookup, doc);
                }
                if (elementsToSign == null || elementsToSign.size() == 0) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement",
                            new Object[] { nmSpace + ", " + elemName });
                }
                for (Element elementToSign : elementsToSign) {
                    TransformParameterSpec transformSpec = null;
                    if (wssConfig.isWsiBSPCompliant()) {
                        List<String> prefixes = getInclusivePrefixes(elementToSign);
                        transformSpec = new ExcC14NParameterSpec(prefixes);
                    }
                    Transform transform = signatureFactory.newTransform(WSConstants.C14N_EXCL_OMIT_COMMENTS,
                            transformSpec);
                    javax.xml.crypto.dsig.Reference reference = signatureFactory.newReference(
                            "#" + setWsuId(elementToSign), digestMethod, Collections.singletonList(transform),
                            null, null);
                    referenceList.add(reference);
                    wsDocInfo.addTokenElement(elementToSign, false);
                }
            }
        } catch (Exception ex) {
            log.error("", ex);
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
        }
    }

    return referenceList;
}