Example usage for javax.xml.crypto.dsig.spec ExcC14NParameterSpec ExcC14NParameterSpec

List of usage examples for javax.xml.crypto.dsig.spec ExcC14NParameterSpec ExcC14NParameterSpec

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig.spec ExcC14NParameterSpec ExcC14NParameterSpec.

Prototype

public ExcC14NParameterSpec(List<String> prefixList) 

Source Link

Document

Creates a ExcC14NParameterSpec with the specified list of prefixes.

Usage

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

/**
 * Initialize a WSSec Signature./*from  w  w  w. java2 s .co m*/
 * 
 * The method sets up and initializes a WSSec 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 cr An instance of the Crypto API to handle keystore and certificates
 * @param secHeader The security header that will hold the Signature. This is used
 *                   to construct namespace prefixes for Signature. This method
 * @throws WSSecurityException
 */
public void prepare(Document doc, Crypto cr, WSSecHeader secHeader) throws WSSecurityException {
    //
    // Gather some info about the document to process and store it for
    // retrieval
    //
    crypto = cr;
    document = doc;
    wsDocInfo = new WSDocInfo(doc);
    wsDocInfo.setCrypto(cr);
    securityHeader = secHeader.getSecurityHeader();

    //
    // At first get the security token (certificate) according to the parameters.
    //
    X509Certificate[] certs = getSigningCerts();

    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("KI-", keyInfo);
    if (!useCustomSecRef) {
        secRef = new SecurityTokenReference(doc);
        strUri = getWsConfig().getIdAllocator().createSecureId("STR-", secRef);
        secRef.setID(strUri);

        //
        // Get an initialized XMLSignature element.
        //

        //
        // Prepare and setup the token references for this Signature
        //
        switch (keyIdentifierType) {
        case WSConstants.BST_DIRECT_REFERENCE:
            Reference ref = new Reference(document);
            ref.setURI("#" + certUri);
            if (!useSingleCert) {
                bstToken = new PKIPathSecurity(document);
                ((PKIPathSecurity) bstToken).setX509Certificates(certs, crypto);
                secRef.addTokenType(PKIPathSecurity.PKI_TYPE);
            } else {
                bstToken = new X509Security(document);
                ((X509Security) bstToken).setX509Certificate(certs[0]);
            }
            ref.setValueType(bstToken.getValueType());
            secRef.setReference(ref);
            bstToken.setID(certUri);
            wsDocInfo.addTokenElement(bstToken.getElement(), false);
            break;

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

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

        case WSConstants.SKI_KEY_IDENTIFIER:
            secRef.setKeyIdentifierSKI(certs[0], crypto);
            break;

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

        case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER:
            if (encrKeySha1value != null) {
                secRef.setKeyIdentifierEncKeySHA1(encrKeySha1value);
            } else {
                byte[] digestBytes = WSSecurityUtil.generateDigest(secretKey);
                secRef.setKeyIdentifierEncKeySHA1(Base64.encode(digestBytes));
            }
            secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
            break;

        case WSConstants.CUSTOM_SYMM_SIGNING:
            Reference refCust = new Reference(document);
            if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                refCust.setValueType(customTokenValueType);
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
            } else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
                refCust.setValueType(customTokenValueType);
            } else if (KerberosSecurity.isKerberosToken(customTokenValueType)) {
                secRef.addTokenType(customTokenValueType);
                refCust.setValueType(customTokenValueType);
            } else {
                refCust.setValueType(customTokenValueType);
            }
            refCust.setURI("#" + customTokenId);
            secRef.setReference(refCust);
            break;

        case WSConstants.CUSTOM_SYMM_SIGNING_DIRECT:
            Reference refCustd = new Reference(document);
            if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                refCustd.setValueType(customTokenValueType);
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
            } else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
                refCustd.setValueType(customTokenValueType);
            } else if (KerberosSecurity.isKerberosToken(customTokenValueType)) {
                secRef.addTokenType(customTokenValueType);
                refCustd.setValueType(customTokenValueType);
            } else {
                refCustd.setValueType(customTokenValueType);
            }
            refCustd.setURI(customTokenId);
            secRef.setReference(refCustd);
            break;

        case WSConstants.CUSTOM_KEY_IDENTIFIER:
            if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId);
                secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId);
                secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
            } else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId, true);
                secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
            } else if (SecurityTokenReference.ENC_KEY_SHA1_URI.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId, true);
                secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
            } else if (WSConstants.WSS_KRB_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId, true);
                secRef.addTokenType(WSConstants.WSS_GSS_KRB_V5_AP_REQ);
            }
            break;

        case WSConstants.KEY_VALUE:
            java.security.PublicKey publicKey = certs[0].getPublicKey();

            try {
                KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey);
                keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(keyValue), keyInfoUri);
            } catch (java.security.KeyException ex) {
                log.error("", ex);
                throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
            }
            break;
        default:
            throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId");
        }
    }

    if (keyIdentifierType != WSConstants.KEY_VALUE) {
        XMLStructure structure = new DOMStructure(secRef.getElement());
        wsDocInfo.addTokenElement(secRef.getElement(), false);
        keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(structure), keyInfoUri);
    }
}

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

/**
 * Initialize a WSSec SAML Signature./*from  w  w w.  ja  va  2  s .c o  m*/
 * 
 * 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:com.vmware.identity.saml.impl.TokenAuthorityImpl.java

/**
 * Creates a list of transform part of Reference section in Signature
 *
 * @return/*from  ww  w.j ava  2  s .co  m*/
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 */
private List<Transform> createTransforms() {
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();

    List<Transform> transforms = new ArrayList<Transform>(2);

    List<String> prefixList = new ArrayList<String>(2);
    prefixList.add(XMLConstants.XSD_PREFIX);
    prefixList.add(XMLConstants.XSI_PREFIX);

    try {
        transforms.add(factory.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));
        transforms.add(
                factory.newTransform(CanonicalizationMethod.EXCLUSIVE, new ExcC14NParameterSpec(prefixList)));
    } catch (Exception e) {
        throw new IllegalStateException("Cannot create enveloped or exclusive transform objects.", e);
    }

    log.debug("Created transforms: {} and {}", CanonicalizationMethod.ENVELOPED,
            CanonicalizationMethod.EXCLUSIVE);
    return transforms;
}

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

/**
 * This method adds references to the Signature.
 * //from w w w .java 2 s  .c o  m
 * @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;
}

From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java

private void addSignature(Element wsSecurityHeaderElement, Element tsElement, Element bodyElement)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException, NoSuchProviderException, SOAPException {
    if (null == this.privateKey) {
        return;// w  w  w. j av  a2 s.co  m
    }
    DOMSignContext domSignContext = new DOMSignContext(this.privateKey, wsSecurityHeaderElement);
    domSignContext.setDefaultNamespacePrefix("ds");
    domSignContext.setIdAttributeNS(tsElement, WSU_NAMESPACE, "Id");
    domSignContext.setIdAttributeNS(bodyElement, WSU_NAMESPACE, "Id");
    LOG.debug("Timestamp element found: " + (null != domSignContext.getElementById("TS")));
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    List<Reference> references = new LinkedList<Reference>();

    List<String> tsPrefixes = new LinkedList<String>();
    tsPrefixes.add("wsse");
    tsPrefixes.add("S");
    ExcC14NParameterSpec tsTransformSpec = new ExcC14NParameterSpec(tsPrefixes);
    Reference tsReference = xmlSignatureFactory.newReference("#TS",
            xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
            Collections.singletonList(
                    xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, tsTransformSpec)),
            null, null);
    references.add(tsReference);

    if (this.signBody) {
        List<String> bodyPrefixes = new LinkedList<String>();
        ExcC14NParameterSpec bodyTransformSpec = new ExcC14NParameterSpec(bodyPrefixes);
        Reference bodyReference = xmlSignatureFactory.newReference("#Body",
                xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
                Collections.singletonList(
                        xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, bodyTransformSpec)),
                null, null);
        references.add(bodyReference);
    }

    if (this.signBinarySecurityToken) {
        Reference bstReference = xmlSignatureFactory
                .newReference("#X509", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
                        Collections.singletonList(xmlSignatureFactory
                                .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)),
                        null, null);
        references.add(bstReference);
    }

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null),
            xmlSignatureFactory.newSignatureMethod(this.signatureAlgorithm, null), references);

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    Document document = wsSecurityHeaderElement.getOwnerDocument();
    Element securityTokenReferenceElement = document.createElementNS(WSSE_NAMESPACE,
            "wsse:SecurityTokenReference");
    Element referenceElement = document.createElementNS(WSSE_NAMESPACE, "wsse:Reference");
    referenceElement.setAttribute("ValueType",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");
    referenceElement.setAttribute("URI", "#X509");
    securityTokenReferenceElement.appendChild(referenceElement);
    KeyInfo keyInfo = keyInfoFactory
            .newKeyInfo(Collections.singletonList(new DOMStructure(securityTokenReferenceElement)));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo, null, "SIG", null);
    xmlSignature.sign(domSignContext);
}