Example usage for javax.xml.crypto.dsig CanonicalizationMethod EXCLUSIVE

List of usage examples for javax.xml.crypto.dsig CanonicalizationMethod EXCLUSIVE

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig CanonicalizationMethod EXCLUSIVE.

Prototype

String EXCLUSIVE

To view the source code for javax.xml.crypto.dsig CanonicalizationMethod EXCLUSIVE.

Click Source Link

Document

The <a href="http://www.w3.org/2001/10/xml-exc-c14n#">Exclusive Canonical XML (without comments)</a> canonicalization method algorithm URI.

Usage

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

private byte[] getC14nValue(List<Node> nodeList) {
    try {/*w w w .  j ava  2s .  c o m*/
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        for (Node node : nodeList) {
            Canonicalizer c14n = Canonicalizer.getInstance(CanonicalizationMethod.EXCLUSIVE);
            buffer.write(c14n.canonicalizeSubtree(node));
        }
        return buffer.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InvalidCanonicalizerException e) {
        throw new RuntimeException("c14n algo error: " + e.getMessage(), e);
    } catch (CanonicalizationException e) {
        throw new RuntimeException("c14n error: " + e.getMessage(), e);
    }
}

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

private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {// www .j a va  2s  .c  o m
    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM",
            new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
    LOG.debug("xml signature factory: " + signatureFactory.getClass().getName());
    LOG.debug("loader: " + signatureFactory.getClass().getClassLoader());
    XMLSignContext signContext = new DOMSignContext(privateKey, this.tslDocument.getDocumentElement());
    signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null);
    List<Reference> references = new LinkedList<Reference>();
    List<Transform> transforms = new LinkedList<Transform>();
    transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);

    Reference reference = signatureFactory.newReference("#" + tslId, digestMethod, transforms, null, null);
    references.add(reference);

    String signatureId = "xmldsig-" + UUID.randomUUID().toString();
    List<XMLObject> objects = new LinkedList<XMLObject>();
    addXadesBes(signatureFactory, this.tslDocument, signatureId, certificate, references, objects);

    SignatureMethod signatureMethod;
    if (isJava6u18OrAbove()) {
        signatureMethod = signatureFactory
                .newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null);
    } else {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    }
    CanonicalizationMethod canonicalizationMethod = signatureFactory
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);

    List<Object> keyInfoContent = new LinkedList<Object>();

    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance();
    List<Object> x509DataObjects = new LinkedList<Object>();
    x509DataObjects.add(certificate);
    x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(certificate.getIssuerX500Principal().toString(),
            certificate.getSerialNumber()));
    X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
    keyInfoContent.add(x509Data);

    KeyValue keyValue;
    try {
        keyValue = keyInfoFactory.newKeyValue(certificate.getPublicKey());
    } catch (KeyException e) {
        throw new RuntimeException("key exception: " + e.getMessage(), e);
    }
    keyInfoContent.add(keyValue);

    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);

    String signatureValueId = signatureId + "-signature-value";
    XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);
    xmlSignature.sign(signContext);
}

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 {/*w  w  w  .jav a2  s.  c  o 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:com.vmware.identity.saml.impl.TokenAuthorityImpl.java

/**
 * Creates a list of transform part of Reference section in Signature
 *
 * @return/*w w  w .  j  a  v  a2  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:be.fedict.eid.idp.common.saml2.Saml2Util.java

/**
 * Sign DOM document//from  w  w  w.  j ava2 s .  co m
 * 
 * @param documentElement
 *            document to be signed
 * @param nextSibling
 *            next sibling in document, dsig is added before this one
 * @param identity
 *            Identity to sign with
 * @throws NoSuchAlgorithmException
 *             signing algorithm not found
 * @throws InvalidAlgorithmParameterException
 *             invalid signing algo param
 * @throws MarshalException
 *             error marshalling signature
 * @throws XMLSignatureException
 *             error during signing
 */
public static void signDocument(Element documentElement, Node nextSibling, KeyStore.PrivateKeyEntry identity)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {

    // get document ID
    String documentId = documentElement.getAttribute("ID");
    LOG.debug("document ID=" + documentId);

    // fix for recent versions of Apache xmlsec.
    documentElement.setIdAttribute("ID", true);

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");

    XMLSignContext signContext = new DOMSignContext(identity.getPrivateKey(), documentElement, nextSibling);
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");
    javax.xml.crypto.dsig.DigestMethod digestMethod = signatureFactory
            .newDigestMethod(javax.xml.crypto.dsig.DigestMethod.SHA1, null);

    List<javax.xml.crypto.dsig.Transform> transforms = new LinkedList<javax.xml.crypto.dsig.Transform>();
    transforms.add(signatureFactory.newTransform(javax.xml.crypto.dsig.Transform.ENVELOPED,
            (TransformParameterSpec) null));
    javax.xml.crypto.dsig.Transform exclusiveTransform = signatureFactory
            .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);

    Reference reference = signatureFactory.newReference("#" + documentId, digestMethod, transforms, null, null);

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            Collections.singletonList(reference));

    List<Object> keyInfoContent = new LinkedList<Object>();
    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance();
    List<Object> x509DataObjects = new LinkedList<Object>();

    for (X509Certificate certificate : Saml2Util.getCertificateChain(identity)) {
        x509DataObjects.add(certificate);
    }
    javax.xml.crypto.dsig.keyinfo.X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
    keyInfoContent.add(x509Data);
    javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
    xmlSignature.sign(signContext);
}

From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java

private void signXML(Element target, String refId, KeyStoreInfo keyStoreInfo) {

    org.apache.xml.security.Init.init();

    XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(SIGN_FACTORY_TYPE);
    try {// w ww .  j av  a 2 s .c  om
        DigestMethod method = signFactory.newDigestMethod(DigestMethod.SHA1, null);
        Transform transform = signFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
        Reference ref = signFactory.newReference('#' + refId, method, Collections.singletonList(transform),
                null, null);

        CanonicalizationMethod canonMethod = signFactory
                .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
        SignatureMethod signMethod = signFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
        SignedInfo si = signFactory.newSignedInfo(canonMethod, signMethod, Collections.singletonList(ref));

        KeyStore.PrivateKeyEntry keyEntry = getKeyEntry(keyStoreInfo);
        if (keyEntry == null) {
            throw new IllegalStateException("Key is not found in keystore. Alias: " + keyStoreInfo.getAlias());
        }

        KeyInfo ki = getKeyInfo(signFactory, keyEntry);

        DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), target);

        XMLSignature signature = signFactory.newXMLSignature(si, ki);

        signature.sign(dsc);

    } catch (Exception e) {
        throw new STSException("Cannot sign xml document: " + e.getMessage(), e);
    }
}

From source file:org.apache.juddi.v3.client.config.ClientConfig.java

/**
 * Fetches all digital signature related properties for the digital signature utility.
 * warning, this will decrypt all passwords
 * @return a properties object//from   w w  w  .j  av a2  s .c  om
 * @throws Exception 
 * @see DigSigUtil
 * @see Properties
 */
public Properties getDigitalSignatureConfiguration() throws Exception {
    Properties p = new Properties();
    p.setProperty(DigSigUtil.CANONICALIZATIONMETHOD,
            this.config.getString("client.signature.canonicalizationMethod", CanonicalizationMethod.EXCLUSIVE));
    p.setProperty(DigSigUtil.CHECK_TIMESTAMPS,
            ((Boolean) (this.config.getBoolean("client.signature.checkTimestamps", true))).toString());
    p.setProperty(DigSigUtil.CHECK_REVOCATION_STATUS_CRL,
            ((Boolean) (this.config.getBoolean("client.signature.checkRevocationCRL", true))).toString());
    p.setProperty(DigSigUtil.CHECK_REVOCATION_STATUS_OCSP,
            ((Boolean) (this.config.getBoolean("client.signature.checkRevocationOCSP", true))).toString());
    p.setProperty(DigSigUtil.CHECK_TRUST_CHAIN,
            ((Boolean) (this.config.getBoolean("client.signature.checkTrust", true))).toString());

    p.setProperty(DigSigUtil.SIGNATURE_KEYSTORE_FILE,
            this.config.getString("client.signature.signingKeyStorePath", ""));
    p.setProperty(DigSigUtil.SIGNATURE_KEYSTORE_FILETYPE,
            this.config.getString("client.signature.signingKeyStoreType", ""));

    if (this.config.getBoolean("client.signature.signingKeyPassword[@isPasswordEncrypted]", false)) {
        String enc = this.config.getString("client.signature.signingKeyPassword", "");
        String prov = this.config.getString("client.signature.signingKeyPassword[@cryptoProvider]", "");
        p.setProperty(DigSigUtil.SIGNATURE_KEYSTORE_KEY_PASSWORD, CryptorFactory.getCryptor(prov).decrypt(enc));
    } else {
        log.warn("Hey, you should consider encrypting your key password!");
        p.setProperty(DigSigUtil.SIGNATURE_KEYSTORE_KEY_PASSWORD,
                this.config.getString("client.signature.signingKeyPassword", ""));
    }
    if (this.config.getBoolean("client.signature.signingKeyStoreFilePassword[@isPasswordEncrypted]", false)) {
        String enc = this.config.getString("client.signature.signingKeyStoreFilePassword", "");
        String prov = this.config.getString("client.signature.signingKeyStoreFilePassword[@cryptoProvider]",
                "");
        p.setProperty(DigSigUtil.SIGNATURE_KEYSTORE_FILE_PASSWORD,
                CryptorFactory.getCryptor(prov).decrypt(enc));
    } else {
        log.warn("Hey, you should consider encrypting your keystore password!");
        p.setProperty(DigSigUtil.SIGNATURE_KEYSTORE_FILE_PASSWORD,
                this.config.getString("client.signature.signingKeyStoreFilePassword", ""));
    }

    p.setProperty(DigSigUtil.SIGNATURE_KEYSTORE_KEY_ALIAS,
            this.config.getString("client.signature.signingKeyAlias", ""));
    p.setProperty(DigSigUtil.SIGNATURE_METHOD, this.config.getString("client.signature.signatureMethod",
            "http://www.w3.org/2000/09/xmldsig#rsa-sha1"));
    p.setProperty(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SUBJECTDN,
            this.config.getString("client.signature.keyInfoInclusionSubjectDN", "true"));
    p.setProperty(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_BASE64,
            this.config.getString("client.signature.keyInfoInclusionBase64PublicKey", "true"));
    p.setProperty(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SERIAL,
            this.config.getString("client.signature.keyInfoInclusionSerial", "true"));

    p.setProperty(DigSigUtil.SIGNATURE_OPTION_DIGEST_METHOD,
            this.config.getString("client.signature.digestMethod", "http://www.w3.org/2000/09/xmldsig#sha1"));

    p.setProperty(DigSigUtil.TRUSTSTORE_FILE, this.config.getString("client.signature.trustStorePath", ""));
    p.setProperty(DigSigUtil.TRUSTSTORE_FILETYPE, this.config.getString("client.signature.trustStoreType", ""));

    if (this.config.getBoolean("client.signature.trustStorePassword[@isPasswordEncrypted]", false)) {
        String enc = this.config.getString("client.signature.trustStorePassword", "");
        String prov = this.config.getString("client.signature.trustStorePassword[@cryptoProvider]", "");
        p.setProperty(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, CryptorFactory.getCryptor(prov).decrypt(enc));
    } else {
        log.warn("Hey, you should consider encrypting your trust store password!");
        p.setProperty(DigSigUtil.TRUSTSTORE_FILE_PASSWORD,
                this.config.getString("client.signature.trustStorePassword", ""));
    }

    return p;
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception {
    Reference ref = initReference(fac);
    String cm = null;//ww  w .j  av a2  s  .c  o  m
    cm = map.getProperty(CANONICALIZATIONMETHOD);
    String sigmethod = null;
    sigmethod = map.getProperty(SIGNATURE_METHOD);
    if (sigmethod == null) {
        sigmethod = SignatureMethod.RSA_SHA1;
    }
    if (cm == null) {
        cm = CanonicalizationMethod.EXCLUSIVE;
    }
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(cm, (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(sigmethod, null), Collections.singletonList(ref));
    return si;
}

From source file:org.asimba.wa.integrationtest.saml2.model.Response.java

/**
 * Requires the responseDocument to be already initialized, just adding another
 * Signature section to the existing documnet
 * @param signatureHelper/*w  w  w .  ja v  a 2s.  c  om*/
 * @return
 */
public String getMessageWithSignedAssertion(SignatureHelper signatureHelper) {
    if (_responseDocument == null) {
        try {
            _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true);
        } catch (OAException | XMLStreamException e) {
            _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e);
            return null;
        }
    }

    KeyPair keypair = signatureHelper.getKeyPairFromKeystore();

    // Set signing context with PrivateKey and root of the Document
    Node localRoot = _assertion.getAssertionNode();
    signatureHelper.tagIdAttributes(localRoot.getOwnerDocument());

    DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), localRoot);

    // Get SignatureFactory for creating signatures in DOM:
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    Reference refAssertion = null;
    SignedInfo si = null;
    XMLSignature signature = null;

    try {
        // Create reference for "" -> Assertion in the document
        // SAML requires enveloped transform
        List<Transform> transformsList = new ArrayList<>();
        transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null));

        refAssertion = fac.newReference("#" + getAssertion().getId(),
                fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null);

        // Create SignedInfo (SAML2: Exclusive with or without comments is specified)
        // .. some selection here; nothing fancy, just trying to switch based on signing key format
        String sigMethod;
        String keyAlg = keypair.getPrivate().getAlgorithm();
        if (keyAlg.contains("RSA")) {
            sigMethod = SignatureMethod.RSA_SHA1;
        } else if (keyAlg.contains("DSA")) {
            sigMethod = SignatureMethod.DSA_SHA1;
        } else {
            _logger.error("Unknown signing key algorithm: {}", keyAlg);
            return null;
        }

        si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(sigMethod, null), Collections.singletonList(refAssertion));

        // Add KeyInfo to the document:
        KeyInfoFactory kif = fac.getKeyInfoFactory();

        // .. get key from the generated keypair:
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

        signature = fac.newXMLSignature(si, ki);

        // before:
        _logger.info("Signing assertion in document");
        //         _logger.info("Document to sign:\n{}", XMLUtils.getStringFromDocument(localRoot.getOwnerDocument()));

        // Sign!
        signature.sign(dsc);

        return XMLUtils.getStringFromDocument(localRoot.getOwnerDocument());

    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        _logger.error("Could not create reference to signable content: {}", e.getMessage(), e);
        return null;
    } catch (KeyException e) {
        _logger.error("Could not establish key info: {}", e.getMessage(), e);
        return null;
    } catch (MarshalException | XMLSignatureException e) {
        _logger.error("Error signing document: {}", e.getMessage(), e);
        return null;
    } catch (OAException e) {
        _logger.error("Error creating string from XML document: {}", e.getMessage(), e);
        return null;
    }
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

/**
 * This will sign a SAMLR2 Identity artifact (assertion, request or response) represeted as a DOM tree
 * The signature will be inserted as the first child of the root element.
 *
 * @param doc//from  w w  w .  j  a va 2s.co m
 * @param id
 * @return
 */
protected Document sign(Document doc, String id) throws SamlR2SignatureException {
    try {

        Certificate cert = keyResolver.getCertificate();

        // Create a DOM XMLSignatureFactory that will be used to generate the
        // enveloped signature
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider);

        if (logger.isDebugEnabled())
            logger.debug("Creating XML DOM Digital Siganture (not signing yet!)");

        // Create a Reference to the enveloped document and
        // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
        // The URI must be the assertion ID

        List<Transform> transforms = new ArrayList<Transform>();
        transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        // Magically, this solves assertion DS validation when embedded in a signed response :)
        transforms.add(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null));

        Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transforms,
                null, null);

        // Use signature method based on key algorithm.
        String signatureMethod = SignatureMethod.DSA_SHA1;
        if (keyResolver.getPrivateKey().getAlgorithm().equals("RSA"))
            signatureMethod = SignatureMethod.RSA_SHA1;

        logger.debug("Using signature method " + signatureMethod);

        // Create the SignedInfo, with the X509 Certificate
        /*
        SignedInfo si = fac.newSignedInfo
            (fac.newCanonicalizationMethod
                    (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                            (C14NMethodParameterSpec) null),
                    fac.newSignatureMethod(signatureMethod, null),
                    Collections.singletonList(ref));
         */
        SignedInfo si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref));

        // Create a KeyInfo and add the Certificate to it
        KeyInfoFactory kif = fac.getKeyInfoFactory();

        X509Data kv = kif.newX509Data(Collections.singletonList(cert));
        //KeyValue kv = kif.newKeyValue(keyResolver.getCertificate().getPublicKey());

        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
        javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

        if (logger.isDebugEnabled())
            logger.debug("Signing SAMLR2 Identity Artifact ...");

        // Create a DOMSignContext and specify the DSA PrivateKey and
        // location of the resulting XMLSignature's parent element
        DOMSignContext dsc = new DOMSignContext(keyResolver.getPrivateKey(), doc.getDocumentElement(),
                doc.getDocumentElement().getFirstChild());

        // Sign the assertion
        signature.sign(dsc);

        if (logger.isDebugEnabled())
            logger.debug("Signing SAMLR2 Identity Artifact ... DONE!");

        return doc;

    } catch (NoSuchAlgorithmException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (XMLSignatureException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (MarshalException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (SSOKeyResolverException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    }
}