Example usage for javax.xml.crypto.dsig XMLSignatureFactory newReference

List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newReference

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig XMLSignatureFactory newReference.

Prototype

public abstract Reference newReference(String uri, DigestMethod dm, List<? extends Transform> transforms,
        String type, String id);

Source Link

Document

Creates a Reference with the specified parameters.

Usage

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

private Reference initReference(XMLSignatureFactory fac)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    List transformers = new ArrayList();
    transformers.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));

    String dm = map.getProperty(SIGNATURE_OPTION_DIGEST_METHOD);
    if (dm == null) {
        dm = DigestMethod.SHA1;/*from w  ww  .  jav a  2 s  . co  m*/
    }
    Reference ref = fac.newReference("", fac.newDigestMethod(dm, null), transformers, null, null);
    return ref;
}

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

/**
 * This method adds references to the Signature.
 * /*from  w w  w .  j a v  a  2s  .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:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java

public String getSignedRequest(int format, InputStream keystoreStream, String keystorePassword, String keyAlias,
        String keyPassword) {/*from  w w  w .ja  va  2 s  . com*/
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    DocumentBuilder builder;
    Document doc;
    try {
        builder = dbf.newDocumentBuilder();
        doc = builder.parse(new InputSource(new ByteArrayInputStream(getRequest(plain).getBytes("utf-8"))));

        // Prepare doc by marking attributes as referenceable:
        tagIdAttributes(doc);

        // Prepare cryptographic environemnt
        KeyStore keystore = getKeystore("JKS", keystoreStream, keystorePassword);
        if (keystore == null)
            return null;

        KeyPair kp;

        kp = getKeyPairFromKeystore(keystore, keyAlias, keyPassword);
        if (kp == null) {
            // Generate key, to prove that it works...
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
            kpg.initialize(512);
            kp = kpg.generateKeyPair();
        }

        // Set signing context with PrivateKey and root of the Document
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());

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

        // Create reference for "" -> root of the document
        // SAML requires enveloped transform
        Reference ref = fac.newReference("#" + this._id, fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                null, null);

        // Create SignedInfo (SAML2: Exclusive with or without comments is specified)
        SignedInfo si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

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

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

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

        String before = docToString(doc);

        // Sign!
        signature.sign(dsc);

        _authnRequestDocument = doc; // persist, as we've worked hard for it

        String after = docToString(doc);

        if (_logger.isDebugEnabled()) {
            _logger.debug("Before: {}", before);
            _logger.debug("After : {}", after);
        }

        return after;

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // key generation exception
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        // digest algorithm selection exception
        e.printStackTrace();
    } catch (KeyException e) {
        // when key-value was not available (when adding to KeyInfo)
        e.printStackTrace();
    } catch (MarshalException e) {
        // sign didn't work:
        e.printStackTrace();
    } catch (XMLSignatureException e) {
        // sign didn't work:
        e.printStackTrace();
    }
    return null;
}

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

public String getSignedMessage(SignatureHelper signatureHelper) {
    if (_responseDocument == null) {
        try {/*from  w w w.  ja  va 2  s.  c  o  m*/
            _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true);
        } catch (OAException | XMLStreamException e) {
            _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e);
            return null;
        }
    }

    signatureHelper.tagIdAttributes(_responseDocument);

    KeyPair keypair = signatureHelper.getKeyPairFromKeystore();

    // Set signing context with PrivateKey and root of the Document
    DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), _responseDocument.getDocumentElement());

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

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

    try {
        // Create reference for "" -> root of 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));

        ref = fac.newReference("#" + 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_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(sigMethod, null), Collections.singletonList(ref));

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

        // Sign!
        signature.sign(dsc);

        String s = XMLUtils.getStringFromDocument(_responseDocument);
        _logger.info("Document after signing whole message:\n{}", s);
        return s;

    } 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.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//from   w ww .j  a  va  2s . c o  m
 * @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 ww . j  ava2 s.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);
    }
}

From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java

/**
 * Sign a simple DOM document using the configured JSR 105 Provider
 *//*from  w  w  w . jav a 2  s.  com*/
@Test
public void simpleDocumentSign() throws Exception {

    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "src/test/resources/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("target/signature.xml");

    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    PublicKey publicKey = cert.getPublicKey();

    // Create a DOM XMLSignatureFactory that will be used to generate the
    // enveloped signature
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
            (Provider) Class.forName(providerName).newInstance());

    // Create a Reference to the enveloped document (in this case we are
    // signing the whole document, so a URI of "" signifies that) and
    // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
    Reference ref = fac.newReference("#12345", fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    SignedInfo si = fac.newSignedInfo(
            fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Instantiate the document to be signed
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //Build a sample document. It will look something like:
    //<!-- Comment before -->
    //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1" ID="12345">Some simple text
    //</apache:RootElement>
    //<!-- Comment after -->
    doc.appendChild(doc.createComment(" Comment before "));

    Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement");

    root.setAttributeNS(null, "ID", "12345");

    root.setAttributeNS(null, "attr1", "test1");
    root.setAttributeNS(null, "attr2", "test2");
    root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:foo",
            "http://example.org/#foo");
    root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test");

    root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:apache",
            "http://www.apache.org/ns/#app1");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

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

    // Create the XMLSignature (but don't sign it yet)
    KeyInfoFactory kif = fac.getKeyInfoFactory();

    X509Data kv = kif.newX509Data(Collections.singletonList(cert));

    // Create a KeyInfo and add the KeyValue to it
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
    javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);

    // TODO : Verify signature ?

    // output the resulting document
    FileOutputStream f = new FileOutputStream(signatureFile);
    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();

}

From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java

/**
 * Sign a SAMLR2 Assertion using the configured JSR 105 Provider
 *///from   www  .  j  a  v  a2s . c  o  m
@Test
public void assertionSign() throws Exception {
    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "src/test/resources/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File assertionFile = new File("src/test/resources/assertion-001.xml");
    File signatureFile = new File("target/assertion-signed-001.xml");

    JAXBContext context = JAXBContext.newInstance("oasis.names.tc.saml._2_0.assertion");
    Unmarshaller um = context.createUnmarshaller();

    JAXBElement jaxbElement = (JAXBElement) um.unmarshal(assertionFile);

    AssertionType assertion = (AssertionType) jaxbElement.getValue();

    // Unmarshall the assertion
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    PublicKey publicKey = cert.getPublicKey();

    // Create a DOM XMLSignatureFactory that will be used to generate the
    // enveloped signature
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
            (Provider) Class.forName(providerName).newInstance());

    // Create a Reference to the enveloped document (in this case we are
    // signing the whole document, so a URI of "" signifies that) and
    // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
    Reference ref = fac.newReference("#" + assertion.getID(), fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    SignedInfo si = fac.newSignedInfo(
            fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Instantiate the document to be signed
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    Marshaller m = context.createMarshaller();
    m.marshal(jaxbElement, doc);

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

    // Create the XMLSignature (but don't sign it yet)
    KeyInfoFactory kif = fac.getKeyInfoFactory();

    X509Data kv = kif.newX509Data(Collections.singletonList(cert));

    // Create a KeyInfo and add the KeyValue to it
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);
    // output the resulting document

    FileOutputStream f = new FileOutputStream(signatureFile);
    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
}

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.jav a2 s  .  c om*/
    }
    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);
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java

@Test
public void testJsr105SignatureExternalXML() throws Exception {
    KeyPair keyPair = PkiTestUtils.generateKeyPair();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element rootElement = document.createElementNS("urn:test", "tns:root");
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:test");
    document.appendChild(rootElement);/* w w  w . j  av  a  2  s.  c  om*/
    Element dataElement = document.createElementNS("urn:test", "tns:data");
    dataElement.setAttributeNS(null, "Id", "id-1234");
    dataElement.setTextContent("data to be signed");
    rootElement.appendChild(dataElement);

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

    XMLSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document.getDocumentElement());
    signContext.setURIDereferencer(new MyURIDereferencer());
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);

    List<Transform> transforms = new LinkedList<Transform>();
    Transform transform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(transform);
    Reference reference = signatureFactory.newReference("/helloworld.xml", digestMethod, transforms, null,
            null);

    DOMReference domReference = (DOMReference) reference;
    assertNull(domReference.getCalculatedDigestValue());
    assertNull(domReference.getDigestValue());

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

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null);

    DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature;
    domXmlSignature.marshal(document.getDocumentElement(), "ds", (DOMCryptoContext) signContext);
    domReference.digest(signContext);
    // xmlSignature.sign(signContext);
    // LOG.debug("signed document: " + toString(document));

    Element nsElement = document.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    Node digestValueNode = XPathAPI.selectSingleNode(document, "//ds:DigestValue", nsElement);
    assertNotNull(digestValueNode);
    String digestValueTextContent = digestValueNode.getTextContent();
    LOG.debug("digest value text content: " + digestValueTextContent);
    assertFalse(digestValueTextContent.isEmpty());
}