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

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

Introduction

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

Prototype

public static XMLSignatureFactory getInstance(String mechanismType, String provider)
        throws NoSuchProviderException 

Source Link

Document

Returns an XMLSignatureFactory that supports the requested XML processing mechanism and representation type (ex: "DOM"), as supplied by the specified provider.

Usage

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

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

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

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

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

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

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

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

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);/*from w w w. j  a  va2s  . c o m*/

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

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

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

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

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

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

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

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

    digestReferences(signContext, references);

    return signature;

}

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

private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {/*  w ww  .  j  av  a  2 s  .  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:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

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

    try {/*from   w  ww.j av a2s.  c  om*/
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

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

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

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

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

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

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

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

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

        Element unsignedSignaturePropertiesNode = getUnsignedSignatureProperties(signatureElement);

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

        buffer.write(getC14nValue(timeStampNodesXadesA));

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

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

@Override
public SignatureCryptographicVerification checkIntegrity(DSSDocument detachedDocument) {

    final SignatureCryptographicVerification scv = new SignatureCryptographicVerification();

    final CertificateToken certToken = getSigningCertificate().getCertToken();
    if (certToken != null) {

        final PublicKey publicKey = certToken.getCertificate().getPublicKey();
        final KeySelector keySelector = KeySelector.singletonKeySelector(publicKey);

        /**/*w  w w  .  jav a 2 s. c o m*/
         * Creating a Validation Context<br>
         * We create an XMLValidateContext instance containing input parameters for validating the signature. Since we
         * are using DOM, we instantiate a DOMValidateContext instance (a subclass of XMLValidateContext), and pass it
         * two parameters, a KeyValueKeySelector object and a reference to the Signature element to be validated (which
         * is the first entry of the NodeList we generated earlier):
         */
        final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureElement);
        try {

            URIDereferencer dereferencer = new ExternalFileURIDereferencer(detachedDocument);
            valContext.setURIDereferencer(dereferencer);
            /**
             * This property controls whether or not the digested Reference objects will cache the dereferenced content
             * and pre-digested input for subsequent retrieval via the Reference.getDereferencedData and
             * Reference.getDigestInputStream methods. The default value if not specified is Boolean.FALSE.
             */
            valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);

            /**
             * Unmarshalling the XML Signature<br>
             * We extract the contents of the Signature element into an XMLSignature object. This process is called
             * unmarshalling. The Signature element is unmarshalled using an XMLSignatureFactory object. An application
             * can obtain a DOM implementation of XMLSignatureFactory by calling the following line of code:
             */

            // These providers do not support ECDSA algorithm
            // factory = XMLSignatureFactory.getInstance("DOM");
            // factory = XMLSignatureFactory.getInstance("DOM", "XMLDSig");
            // factory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI());

            // This provider support ECDSA signature
            /**
             * ApacheXMLDSig / Apache Santuario XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory; C14N 1.0, C14N
             * 1.1, Exclusive C14N, Base64, Enveloped, XPath, XPath2, XSLT TransformServices)<br>
             * If this library is used than the same library must be used for the URIDereferencer.
             */
            final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", xmlProvider);

            /**
             * We then invoke the unmarshalXMLSignature method of the factory to unmarshal an XMLSignature object, and
             * pass it the validation context we created earlier:
             */
            final XMLSignature signature = factory.unmarshalXMLSignature(valContext);
            //System.out.println("XMLSignature class: " + signature.getClass());

            // Austrian specific signature
            //org.apache.xml.security.signature.XMLSignature signature_ = null;
            // try {
            // signature_ = new org.apache.xml.security.signature.XMLSignature(signatureElement, "");
            // } catch (Exception e) {
            //
            // throw new DSSException(e);
            // }
            // signature.addResourceResolver(new XPointerResourceResolver(signatureElement));

            //signature_.getSignedInfo().verifyReferences();//getVerificationResult(1);
            /**
             * In case of org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI() provider, the ID attributes need to be set
             * manually.<br>
             * The DSSXMLUtils.recursiveIdBrowse(...) method do not take into account the XML outside of the Signature
             * tag. It prevents some signatures to be validated.<br>
             *
             * Solution: the following lines where added:
             */
            final Document document = signatureElement.getOwnerDocument();
            final Element rootElement = document.getDocumentElement();
            if (rootElement.hasAttribute(DSSXMLUtils.ID_ATTRIBUTE_NAME)) {

                valContext.setIdAttributeNS(rootElement, null, DSSXMLUtils.ID_ATTRIBUTE_NAME);
            }

            DSSXMLUtils.recursiveIdBrowse(valContext, rootElement);

            /**
             * Validating the XML Signature<br>
             * Now we are ready to validate the signature. We do this by invoking the validate method on the
             * XMLSignature object, and pass it the validation context as follows:
             */
            boolean coreValidity = false;
            try {

                coreValidity = signature.validate(valContext);
            } catch (XMLSignatureException e) {

                scv.setErrorMessage("Signature validation: " + e.getMessage());
            }
            boolean signatureValidity = coreValidity;
            boolean dataFound = true;
            boolean dataHashValid = true;

            /**
             * If the XMLSignature.validate method returns false, we can try to narrow down the cause of the failure.
             * There are two phases in core XML Signature validation: <br>
             * - Signature validation (the cryptographic verification of the signature)<br>
             * - Reference validation (the verification of the digest of each reference in the signature)<br>
             * Each phase must be successful for the signature to be valid. To check if the signature failed to
             * cryptographically validate, we can check the status, as follows:
             */

            try {

                signatureValidity = signature.getSignatureValue().validate(valContext);
            } catch (XMLSignatureException e) {

                scv.setErrorMessage(e.getMessage());
            }

            @SuppressWarnings("unchecked")
            final List<Reference> references = signature.getSignedInfo().getReferences();
            for (Reference reference : references) {

                boolean refHashValidity = false;
                try {

                    refHashValidity = reference.validate(valContext);
                } catch (XMLSignatureException e) {

                    scv.setErrorMessage(reference.getURI() + ": " + e.getMessage());
                }
                dataHashValid = dataHashValid && refHashValidity;
                if (LOG.isLoggable(Level.INFO)) {
                    LOG.info("Reference hash validity checked: " + reference.getURI() + "=" + refHashValidity);
                }
                final Data data = reference.getDereferencedData();
                dataFound = dataFound && (data != null);

                final InputStream digestInputStream = reference.getDigestInputStream();
                if (data != null && digestInputStream != null) {

                    // The references are saved for later treatment in -A level.
                    try {

                        IOUtils.copy(digestInputStream, referencesDigestOutputStream);
                    } catch (IOException e) {
                    }
                }
            }
            scv.setReferenceDataFound(dataFound);
            scv.setReferenceDataIntact(dataHashValid);
            scv.setSignatureIntegrity(signatureValidity);
        } catch (MarshalException e) {

            scv.setErrorMessage(e.getMessage());
        }
    } else {

        scv.setErrorMessage(
                "Unable to proceed with the signature cryptographic verification. There is no signing certificate!");
    }
    return scv;
}

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

public void validate(RoleDescriptorType md, Document doc, Node root) throws SamlR2SignatureException {
    try {/*  w w  w. j a  v  a  2s.  c  om*/

        // Check for duplicate IDs among XML elements
        NodeList nodes = evaluateXPath(doc, "//*/@ID");
        boolean duplicateIdExists = false;
        List<String> ids = new ArrayList<String>();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (ids.contains(node.getNodeValue())) {
                duplicateIdExists = true;
                logger.error("Duplicated Element ID in XML Document : " + node.getNodeValue());
            }
            ids.add(node.getNodeValue());
        }
        if (duplicateIdExists) {
            throw new SamlR2SignatureException("Duplicate IDs in document ");
        }

        // TODO : Check that the Signature references the root element (the one used by the application)
        // Keep in mind that signature reference might be an XPath expression ?!

        // We know that in SAML, the root element is the element used by the application, we just need to make sure that
        // the root element is the one referred by the signature

        Node rootIdAttr = root.getAttributes().getNamedItem("ID");
        if (rootIdAttr == null)
            throw new SamlR2SignatureException("SAML document does not have an ID ");

        // Find Signature element
        NodeList signatureNodes = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodes.getLength() == 0) {
            throw new SamlR2SignatureException("Cannot find Signature elements");
        }

        // Create a DOM XMLSignatureFactory that will be used to unmarshal the
        // document containing the XMLSignature
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider);

        // Create a DOMValidateContext and specify a KeyValue KeySelector
        // and document context

        // Validate all Signature elements
        boolean rootIdMatched = false;
        for (int k = 0; k < signatureNodes.getLength(); k++) {

            DOMValidateContext valContext = new DOMValidateContext(new RawX509KeySelector(),
                    signatureNodes.item(k));

            // unmarshal the XMLSignature
            XMLSignature signature = fac.unmarshalXMLSignature(valContext);

            // Validate the XMLSignature (generated above)
            boolean coreValidity = signature.validate(valContext);

            // Check core validation status
            if (!coreValidity) {

                if (logger.isDebugEnabled())
                    logger.debug("Signature failed core validation");

                boolean sv = signature.getSignatureValue().validate(valContext);

                if (logger.isDebugEnabled())
                    logger.debug("signature validation status: " + sv);
                // check the validation status of each Reference (should be only one!)
                Iterator i = signature.getSignedInfo().getReferences().iterator();
                boolean refValid = true;
                for (int j = 0; i.hasNext(); j++) {

                    Reference ref = (Reference) i.next();
                    boolean b = ref.validate(valContext);
                    if (logger.isDebugEnabled())
                        logger.debug("ref[" + j + "] " + ref.getId() + " validity status: " + b);

                    if (!b) {
                        refValid = b;
                        logger.error("Signature failed reference validation " + ref.getId());
                    }

                }
                throw new SamlR2SignatureValidationException(
                        "Signature failed core validation" + (refValid ? " but passed all Reference validations"
                                : " and some/all Reference validation"));
            }

            if (logger.isDebugEnabled())
                logger.debug("Singnature passed Core validation");

            // The Signature must contain only one reference, and it must be the signed top element's ID.
            List<Reference> refs = signature.getSignedInfo().getReferences();
            if (refs.size() != 1) {
                throw new SamlR2SignatureValidationException(
                        "Invalid number of 'Reference' elements in signature : " + refs.size() + " ["
                                + signature.getId() + "]");
            }

            Reference reference = refs.get(0);
            String referenceURI = reference.getURI();

            if (referenceURI == null || !referenceURI.startsWith("#"))
                throw new SamlR2SignatureValidationException(
                        "Signature reference URI format not supported " + referenceURI);

            if (referenceURI.substring(1).equals(rootIdAttr.getNodeValue()))
                rootIdMatched = true;

            Key key = signature.getKeySelectorResult().getKey();
            boolean certValidity = validateCertificate(md, key);
            if (!certValidity) {
                throw new SamlR2SignatureValidationException("Signature failed Certificate validation");
            }

            if (logger.isDebugEnabled())
                logger.debug("Signature passed Certificate validation");

        }

        // Check that any of the Signatures matched the root element ID
        if (!rootIdMatched) {
            logger.error("No Signature element refers to signed element (possible signature wrapping attack)");
            throw new SamlR2SignatureValidationException("No Signature element refers to signed element");
        }

    } catch (MarshalException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.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//w w w  . j  av a  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);
    }
}

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

/**
 * Sign a simple DOM document using the configured JSR 105 Provider
 *///w  ww.ja v  a 2 s .  c  om
@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  ww w  .j  a v  a  2 s  .  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.be.fedict.eid.applet.model.XmlSignatureServiceBean.java

private byte[] getXmlSignatureDigestValue(String digestAlgo, List<DigestInfo> digestInfos,
        HttpSession httpSession) throws ParserConfigurationException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException, javax.xml.crypto.dsig.XMLSignatureException,
        TransformerFactoryConfigurationError, TransformerException, MalformedURLException {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();

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

    Key key = new Key() {
        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }//ww w. j  a v  a  2s. com

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };
    XMLSignContext signContext = new DOMSignContext(key, document);
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    List<Reference> references = new LinkedList<Reference>();
    for (DigestInfo digestInfo : digestInfos) {
        byte[] documentDigestValue = digestInfo.digestValue;

        DigestMethod digestMethod = signatureFactory.newDigestMethod(getXmlDigestAlgo(digestInfo.digestAlgo),
                null);

        String uri = FilenameUtils.getName(new File(digestInfo.description).toURI().toURL().getFile());

        Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null,
                documentDigestValue);
        references.add(reference);
    }

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    javax.xml.crypto.dsig.SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod,
            signatureMethod, references);

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null);
    DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature;
    domXmlSignature.marshal(document, "ds", (DOMCryptoContext) signContext);

    Source source = new DOMSource(document);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    xformer.transform(source, result);
    String documentStr = stringWriter.getBuffer().toString();
    httpSession.setAttribute("xmlDocument", documentStr);

    DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
    ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    domSignedInfo.canonicalize(signContext, dataStream);
    byte[] octets = dataStream.toByteArray();

    MessageDigest jcaMessageDigest = MessageDigest.getInstance(digestAlgo);
    byte[] digestValue = jcaMessageDigest.digest(octets);
    return digestValue;
}

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

@Test
public void testJsr105Signature() 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 ww  .j ava 2 s  .c om
    Element dataElement = document.createElementNS("urn:test", "tns:data");
    dataElement.setAttributeNS(null, "Id", "id-1234");
    dataElement.setIdAttribute("Id", true);
    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.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
    Reference reference = signatureFactory.newReference("#id-1234", digestMethod);
    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());
}