Package javax.xml.crypto.dsig

Examples of javax.xml.crypto.dsig.XMLSignatureFactory


    private static org.slf4j.Logger log =
        org.slf4j.LoggerFactory.getLogger(Driver.class);

    public void dsig() throws Exception {

        XMLSignatureFactory fac = XMLSignatureFactory.getInstance
            ("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            fac.newCanonicalizationMethod
                (CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
        }
        long end = System.currentTimeMillis();
        long elapsed = end - start;
        if (log.isDebugEnabled()) {
View Full Code Here


    @SuppressWarnings("unchecked")
    protected void verify(InputStream input, final Message out) throws Exception { //NOPMD
        LOG.debug("Verification of XML signature document started");
        final Document doc = parseInput(input, out);

        XMLSignatureFactory fac;
        // Try to install the Santuario Provider - fall back to the JDK provider if this does
        // not work
        try {
            fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
        } catch (NoSuchProviderException ex) {
            fac = XMLSignatureFactory.getInstance("DOM");
        }

        KeySelector selector = getConfiguration().getKeySelector();
        if (selector == null) {
            throw new IllegalStateException("Wrong configuration. Key selector is missing.");
        }

        DOMValidateContext valContext = new DOMValidateContext(selector, doc);
        valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
        valContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);

        if (getConfiguration().getSecureValidation() == Boolean.TRUE) {
            valContext.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
            valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
        }
        setUriDereferencerAndBaseUri(valContext);

        setCryptoContextProperties(valContext);

        NodeList signatureNodes = getSignatureNodes(doc);

        List<XMLObject> collectedObjects = new ArrayList<XMLObject>(3);
        List<Reference> collectedReferences = new ArrayList<Reference>(3);
        int totalCount = signatureNodes.getLength();
        for (int i = 0; i < totalCount; i++) {

            Element signatureNode = (Element) signatureNodes.item(i);

            valContext.setNode(signatureNode);
            final XMLSignature signature = fac.unmarshalXMLSignature(valContext);

            if (getConfiguration().getXmlSignatureChecker() != null) {
                XmlSignatureChecker.Input checkerInput = new CheckerInputBuilder().message(out).messageBodyDocument(doc)
                        .keyInfo(signature.getKeyInfo()).currentCountOfSignatures(i + 1).currentSignatureElement(signatureNode)
                        .objects(signature.getObjects()).signatureValue(signature.getSignatureValue())
View Full Code Here

    }

    protected Document sign(final Message out) throws Exception { //NOPMD

        try {
            XMLSignatureFactory fac;
            // Try to install the Santuario Provider - fall back to the JDK provider if this does
            // not work
            try {
                fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
            } catch (NoSuchProviderException ex) {
                fac = XMLSignatureFactory.getInstance("DOM");
            }

            final Node node = getMessageBodyNode(out);

            final KeySelector keySelector = getConfiguration().getKeyAccessor().getKeySelector(out);
            if (keySelector == null) {
                throw new XmlSignatureNoKeyException(
                        "Key selector is missing for XML signature generation. Specify a key selector in the configuration.");
            }

            SignatureType signatureType = determineSignatureType(out);

            final List<String> contentReferenceUris = getContentReferenceUris(out, signatureType, node);

            Node lastParent = null;
            // per content reference URI a signature is built; for enveloped and enveloping there is only one content reference URI;
            // only in the detached case there can be several
            for (final String contentReferenceUri : contentReferenceUris) {

                // the method KeyAccessor.getKeyInfo must be called after the method KeyAccessor.getKeySelector, this is part of the interface contract!
                // and this method must be called within the loop over the content reference URIs, because for each signature the key info ID must be different
                final KeyInfo keyInfo = getConfiguration().getKeyAccessor().getKeyInfo(out, node, fac.getKeyInfoFactory());

                String signatureId = getConfiguration().getSignatureId();
                if (signatureId == null) {
                    signatureId = "_" + UUID.randomUUID().toString();
                } else if (signatureId.isEmpty()) {
                    // indicator that no signature Id attribute shall be generated
                    signatureId = null;
                }

                // parent only relevant for enveloped or detached signature
                Node parent = getParentOfSignature(out, node, contentReferenceUri, signatureType);

                XmlSignatureProperties.Input input = new InputBuilder().contentDigestAlgorithm(getDigestAlgorithmUri()).keyInfo(keyInfo)
                        .message(out).messageBodyNode(node).parent(parent).signatureAlgorithm(getConfiguration().getSignatureAlgorithm())
                        .signatureFactory(fac).signatureId(signatureId).contentReferenceUri(contentReferenceUri)
                        .signatureType(signatureType).build();

                XmlSignatureProperties.Output properties = getSignatureProperties(input);

                List<? extends XMLObject> objects = getObjects(input, properties);
                List<? extends Reference> refs = getReferences(input, properties, getKeyInfoId(keyInfo));

                SignedInfo si = createSignedInfo(fac, refs);

                if (parent == null) {
                    // for enveloping signature, create new document
                    parent = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).newDocument();
                }
                lastParent = parent;

                DOMSignContext dsc = createAndConfigureSignContext(parent, keySelector);

                XMLSignature signature = fac.newXMLSignature(si, keyInfo, objects, signatureId, null);
                // generate the signature
                signature.sign(dsc);
            }

            return XmlSignatureHelper.getDocument(lastParent);
View Full Code Here

       
    }

    public Document signDocument(Document document) throws Exception {

        XMLSignatureFactory fac;
        Reference ref;
        SignedInfo si;

       
        // Create a DOMSignContext and specify the RSA PrivateKey and
        // location of the resulting XMLSignature's parent element.
        // Create a DOM XMLSignatureFactory that will be used to
        // generate the enveloped signature.
        fac = XMLSignatureFactory.getInstance("DOM");

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

        // Create the SignedInfo.
        si = fac.newSignedInfo
         (fac.newCanonicalizationMethod
          (CanonicalizationMethod.INCLUSIVE,
           (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
             Collections.singletonList(ref));       
       
        // Create the KeyInfo containing the X509Data.
        KeyInfoFactory kif = fac.getKeyInfoFactory();
        List<Object> x509Content = new ArrayList();
        x509Content.add(cert.getSubjectX500Principal().getName());
        x509Content.add(cert);
        X509Data xd = kif.newX509Data(x509Content);
        ki = kif.newKeyInfo(Collections.singletonList(xd));    

       
       
        DOMSignContext dsc = new DOMSignContext
            (keyEntry.getPrivateKey(), document.getDocumentElement());

        // Create the XMLSignature, but don't sign it yet.
        XMLSignature signature = fac.newXMLSignature(si, ki);

        // Marshal, generate, and sign the enveloped signature.
        signature.sign(dsc);

        return document;
View Full Code Here

        DOMValidateContext valContext = new DOMValidateContext
            (new X509KeySelector(ks), nl.item(0));

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

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

       
        // Validate the XMLSignature.
        boolean coreValidity = signature.validate(valContext);
View Full Code Here

        // and document context.
        DOMValidateContext valContext = new DOMValidateContext
            (new X509KeySelector(ks), nl.item(0));

        // Create a DOM XMLSignatureFactory
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
       
        // Unmarshal the XMLSignature.
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);

        // Validate the XMLSignature.
        coreValidity = signature.validate(valContext);
    
        // Check core validation status.
View Full Code Here

   
    public static void main(String[] unused) throws Exception {
       
     // Create a DOM XMLSignatureFactory that will be used to
     // generate the enveloped signature.
     XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

     // Create a Reference to the enveloped document (in this case,
     // you 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
      ("", 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,
        (C14NMethodParameterSpec) null),
         fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
          Collections.singletonList(ref));
       
    
    
  // Load the KeyStore and get the signing key and certificate.
     KeyStore ks = KeyStore.getInstance("JKS");
     ks.load(new FileInputStream(KEYSTORE), KEYSTORE_PASSWORD.toCharArray());
     KeyStore.PrivateKeyEntry keyEntry =
         (KeyStore.PrivateKeyEntry) ks.getEntry
             (PRIVATE_KEY_ALIAS_IN_KEYSTORE, new KeyStore.PasswordProtection(KEYSTORE_PASSWORD.toCharArray()));
     X509Certificate cert = (X509Certificate) keyEntry.getCertificate();

     // Create the KeyInfo containing the X509Data.
     KeyInfoFactory kif = fac.getKeyInfoFactory();
     List<Object> x509Content = new ArrayList();
     x509Content.add(cert.getSubjectX500Principal().getName());
     x509Content.add(cert);
     X509Data xd = kif.newX509Data(x509Content);
     KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));    
    
  // Instantiate the document to be signed.
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     dbf.setNamespaceAware(true);
     Document doc = dbf.newDocumentBuilder().parse
         (new FileInputStream(DOCUMENT_TO_SIGN));

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

     // Create the XMLSignature, but don't sign it yet.
     XMLSignature signature = fac.newXMLSignature(si, ki);

     // Marshal, generate, and sign the enveloped signature.
     signature.sign(dsc);
    
     //Write signature to a binary file if you desire
View Full Code Here

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

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

        XMLSignatureFactory signFactory = XMLSignatureFactory
                .getInstance(SIGN_FACTORY_TYPE);
        try {
            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: "
View Full Code Here

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

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

        XMLSignatureFactory signFactory = XMLSignatureFactory
                .getInstance(SIGN_FACTORY_TYPE);
        try {
            DigestMethod method = signFactory.newDigestMethod(
                    DigestMethod.SHA1, null);
            Transform transform1 = signFactory.newTransform(
                    Transform.ENVELOPED,
                    (TransformParameterSpec) null);
            Transform transform2 = signFactory.newTransform(
                    CanonicalizationMethod.EXCLUSIVE,
                    (TransformParameterSpec) null);

            Reference ref = signFactory.newReference('#' + refId, method,
                    Arrays.asList(transform1, transform2), 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: "
View Full Code Here

    private static Element signSamlElement(Element element, PrivateKey privKey,
        PublicKey pubKey) {
        try {
            final String providerName = System.getProperty("jsr105Provider",
                JSR_105_PROVIDER);
            final XMLSignatureFactory sigFactory = XMLSignatureFactory
                .getInstance("DOM", (Provider) Class.forName(providerName)
                    .newInstance());

            final List envelopedTransform = Collections
                .singletonList(sigFactory.newTransform(Transform.ENVELOPED,
                    (TransformParameterSpec) null));

            final Reference ref = sigFactory.newReference("", sigFactory
                .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform,
                null, null);

            // Create the SignatureMethod based on the type of key
            SignatureMethod signatureMethod;
            if (pubKey instanceof DSAPublicKey) {
                signatureMethod = sigFactory.newSignatureMethod(
                    SignatureMethod.DSA_SHA1, null);
            } else if (pubKey instanceof RSAPublicKey) {
                signatureMethod = sigFactory.newSignatureMethod(
                    SignatureMethod.RSA_SHA1, null);
            } else {
                throw new RuntimeException(
                    "Error signing SAML element: Unsupported type of key");
            }

            final CanonicalizationMethod canonicalizationMethod = sigFactory
                .newCanonicalizationMethod(
                    CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null);

            // Create the SignedInfo
            final SignedInfo signedInfo = sigFactory.newSignedInfo(
                canonicalizationMethod, signatureMethod, Collections
                    .singletonList(ref));

            // Create a KeyValue containing the DSA or RSA PublicKey
            final KeyInfoFactory keyInfoFactory = sigFactory
                .getKeyInfoFactory();
            final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey);

            // Create a KeyInfo and add the KeyValue to it
            final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections
                .singletonList(keyValuePair));
            // Convert the JDOM document to w3c (Java XML signature API requires
            // w3c
            // representation)
            org.w3c.dom.Element w3cElement = toDom(element);

            // Create a DOMSignContext and specify the DSA/RSA PrivateKey and
            // location of the resulting XMLSignature's parent element
            DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);

            org.w3c.dom.Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
            dsc.setNextSibling(xmlSigInsertionPoint);

            // Marshal, generate (and sign) the enveloped signature
            XMLSignature signature = sigFactory.newXMLSignature(signedInfo,
                keyInfo);
            signature.sign(dsc);

            return toJdom(w3cElement);
View Full Code Here

TOP

Related Classes of javax.xml.crypto.dsig.XMLSignatureFactory

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.