Search in sources :

Example 1 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project camel by apache.

the class XmlSignerProcessor method sign.

protected Document sign(final Message out) throws Exception {
    try {
        XMLSignatureFactory fac;
        // not work
        try {
            fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
        } catch (NoSuchProviderException ex) {
            fac = XMLSignatureFactory.getInstance("DOM");
        }
        final Node node = getMessageBodyNode(out);
        if (getConfiguration().getKeyAccessor() == null) {
            throw new XmlSignatureNoKeyException("Key accessor is missing for XML signature generation. Specify a key accessor in the configuration.");
        }
        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;
        // 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);
            if (parent == null) {
                // for enveloping signature, create new document 
                parent = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).newDocument();
            }
            lastParent = parent;
            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).prefixForXmlSignatureNamespace(getConfiguration().getPrefixForXmlSignatureNamespace()).build();
            XmlSignatureProperties.Output properties = getSignatureProperties(input);
            // the signature properties can overwrite the signature Id
            if (properties != null && properties.getSignatureId() != null && !properties.getSignatureId().isEmpty()) {
                signatureId = properties.getSignatureId();
            }
            List<? extends XMLObject> objects = getObjects(input, properties);
            List<? extends Reference> refs = getReferences(input, properties, getKeyInfoId(keyInfo));
            SignedInfo si = createSignedInfo(fac, refs);
            DOMSignContext dsc = createAndConfigureSignContext(parent, keySelector);
            XMLSignature signature = fac.newXMLSignature(si, keyInfo, objects, signatureId, null);
            // generate the signature
            signature.sign(dsc);
        }
        return XmlSignatureHelper.getDocument(lastParent);
    } catch (XMLSignatureException se) {
        if (se.getCause() instanceof InvalidKeyException) {
            throw new XmlSignatureInvalidKeyException(se.getMessage(), se);
        } else {
            throw new XmlSignatureException(se);
        }
    } catch (GeneralSecurityException e) {
        // like NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException
        throw new XmlSignatureException(e);
    }
}
Also used : XmlSignatureInvalidKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidKeyException) XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) XmlSignatureProperties(org.apache.camel.component.xmlsecurity.api.XmlSignatureProperties) Node(org.w3c.dom.Node) GeneralSecurityException(java.security.GeneralSecurityException) SignatureType(org.apache.camel.component.xmlsecurity.api.SignatureType) KeySelector(javax.xml.crypto.KeySelector) InvalidKeyException(java.security.InvalidKeyException) XmlSignatureInvalidKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidKeyException) SignedInfo(javax.xml.crypto.dsig.SignedInfo) XmlSignatureException(org.apache.camel.component.xmlsecurity.api.XmlSignatureException) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) XmlSignatureNoKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureNoKeyException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) NoSuchProviderException(java.security.NoSuchProviderException) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Example 2 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project cas by apereo.

the class AbstractSamlObjectBuilder method signSamlElement.

/**
     * Sign SAML element.
     *
     * @param element the element
     * @param privKey the priv key
     * @param pubKey  the pub key
     * @return the element
     */
private org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
    try {
        final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);
        final XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
        final List<Transform> envelopedTransform = Collections.singletonList(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory.newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);
        // Create the SignatureMethod based on the type of key
        final SignatureMethod signatureMethod;
        final String algorithm = pubKey.getAlgorithm();
        switch(algorithm) {
            case "DSA":
                signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
                break;
            case "RSA":
                signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
                break;
            default:
                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)
        final Element w3cElement = toDom(element);
        // Create a DOMSignContext and specify the DSA/RSA PrivateKey and
        // location of the resulting XMLSignature's parent element
        final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);
        final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
        dsc.setNextSibling(xmlSigInsertionPoint);
        // Marshal, generate (and sign) the enveloped signature
        final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
        signature.sign(dsc);
        return toJdom(w3cElement);
    } catch (final Exception e) {
        throw new RuntimeException("Error signing SAML element: " + e.getMessage(), e);
    }
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) KeyValue(javax.xml.crypto.dsig.keyinfo.KeyValue) Reference(javax.xml.crypto.dsig.Reference) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) XSString(org.opensaml.core.xml.schema.XSString) SignedInfo(javax.xml.crypto.dsig.SignedInfo) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) Transform(javax.xml.crypto.dsig.Transform)

Example 3 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_signature.

static void test_create_signature() throws Exception {
    System.out.println("* Generating signature.xml");
    // create references
    List<Reference> refs = new ArrayList<Reference>();
    // Reference 1
    refs.add(fac.newReference(STYLESHEET, sha1));
    // Reference 2
    refs.add(fac.newReference(STYLESHEET_B64, sha1, Collections.singletonList(fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), null, null));
    // Reference 3
    refs.add(fac.newReference("#object-1", sha1, Collections.singletonList(fac.newTransform(Transform.XPATH, new XPathFilterParameterSpec("self::text()"))), XMLObject.TYPE, null));
    // Reference 4
    String expr = "\n" + " ancestor-or-self::dsig:SignedInfo                  " + "\n" + "  and                                               " + "\n" + " count(ancestor-or-self::dsig:Reference |           " + "\n" + "      here()/ancestor::dsig:Reference[1]) >         " + "\n" + " count(ancestor-or-self::dsig:Reference)            " + "\n" + "  or                                                " + "\n" + " count(ancestor-or-self::node() |                   " + "\n" + "      id('notaries')) =                             " + "\n" + " count(ancestor-or-self::node())                    " + "\n";
    XPathFilterParameterSpec xfp = new XPathFilterParameterSpec(expr, Collections.singletonMap("dsig", XMLSignature.XMLNS));
    refs.add(fac.newReference("", sha1, Collections.singletonList(fac.newTransform(Transform.XPATH, xfp)), XMLObject.TYPE, null));
    // Reference 5
    refs.add(fac.newReference("#object-2", sha1, Collections.singletonList(fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), XMLObject.TYPE, null));
    // Reference 6
    refs.add(fac.newReference("#manifest-1", sha1, null, Manifest.TYPE, null));
    // Reference 7
    refs.add(fac.newReference("#signature-properties-1", sha1, null, SignatureProperties.TYPE, null));
    // Reference 8
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    refs.add(fac.newReference("", sha1, transforms, null, null));
    // Reference 9
    transforms.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null));
    refs.add(fac.newReference("", sha1, transforms, null, null));
    // Reference 10
    Transform env = fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    refs.add(fac.newReference("#xpointer(/)", sha1, Collections.singletonList(env), null, null));
    // Reference 11
    transforms.clear();
    transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    transforms.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null));
    refs.add(fac.newReference("#xpointer(/)", sha1, transforms, null, null));
    // Reference 12
    refs.add(fac.newReference("#object-3", sha1, null, XMLObject.TYPE, null));
    // Reference 13
    Transform withComments = fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null);
    refs.add(fac.newReference("#object-3", sha1, Collections.singletonList(withComments), XMLObject.TYPE, null));
    // Reference 14
    refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, null, XMLObject.TYPE, null));
    // Reference 15
    withComments = fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null);
    refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, Collections.singletonList(withComments), XMLObject.TYPE, null));
    // Reference 16
    refs.add(fac.newReference("#reference-2", sha1));
    // Reference 17
    refs.add(fac.newReference("#manifest-reference-1", sha1, null, null, "reference-1"));
    // Reference 18
    refs.add(fac.newReference("#reference-1", sha1, null, null, "reference-2"));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, dsaSha1, refs);
    // create keyinfo
    XPathFilterParameterSpec xpf = new XPathFilterParameterSpec("ancestor-or-self::dsig:X509Data", Collections.singletonMap("dsig", XMLSignature.XMLNS));
    RetrievalMethod rm = kifac.newRetrievalMethod("#object-4", X509Data.TYPE, Collections.singletonList(fac.newTransform(Transform.XPATH, xpf)));
    KeyInfo ki = kifac.newKeyInfo(Collections.singletonList(rm), null);
    Document doc = db.newDocument();
    // create objects
    List<XMLStructure> objs = new ArrayList<XMLStructure>();
    // Object 1
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(doc.createTextNode("I am the text."))), "object-1", "text/plain", null));
    // Object 2
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="))), "object-2", "text/plain", Transform.BASE64));
    // Object 3
    Element nc = doc.createElementNS(null, "NonCommentandus");
    nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");
    nc.appendChild(doc.createComment(" Commentandum "));
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(nc)), "object-3", null, null));
    // Manifest
    List<Reference> manRefs = new ArrayList<Reference>();
    // Manifest Reference 1
    manRefs.add(fac.newReference(STYLESHEET, sha1, null, null, "manifest-reference-1"));
    // Manifest Reference 2
    manRefs.add(fac.newReference("#reference-1", sha1));
    // Manifest Reference 3
    List<Transform> manTrans = new ArrayList<Transform>();
    Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));
    Node xslElem = docxslt.getDocumentElement();
    manTrans.add(fac.newTransform(Transform.XSLT, new XSLTTransformParameterSpec(new DOMStructure(xslElem))));
    manTrans.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null));
    manRefs.add(fac.newReference("#notaries", sha1, manTrans, null, null));
    objs.add(fac.newXMLObject(Collections.singletonList(fac.newManifest(manRefs, "manifest-1")), null, null, null));
    // SignatureProperties
    Element sa = doc.createElementNS("urn:demo", "SignerAddress");
    sa.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:demo");
    Element ip = doc.createElementNS("urn:demo", "IP");
    ip.appendChild(doc.createTextNode("192.168.21.138"));
    sa.appendChild(ip);
    SignatureProperty sp = fac.newSignatureProperty(Collections.singletonList(new DOMStructure(sa)), "#signature", null);
    SignatureProperties sps = fac.newSignatureProperties(Collections.singletonList(sp), "signature-properties-1");
    objs.add(fac.newXMLObject(Collections.singletonList(sps), null, null, null));
    // Object 4
    List<Object> xds = new ArrayList<Object>();
    xds.add("CN=User");
    xds.add(kifac.newX509IssuerSerial("CN=User", new BigInteger("45ef2729", 16)));
    xds.add(signingCert);
    objs.add(fac.newXMLObject(Collections.singletonList(kifac.newX509Data(xds)), "object-4", null, null));
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki, objs, "signature", null);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document envDoc = dbf.newDocumentBuilder().parse(new FileInputStream(ENVELOPE));
    Element ys = (Element) envDoc.getElementsByTagName("YoursSincerely").item(0);
    DOMSignContext dsc = new DOMSignContext(signingKey, ys);
    dsc.setURIDereferencer(httpUd);
    sig.sign(dsc);
    //      StringWriter sw = new StringWriter();
    //        dumpDocument(envDoc, sw);
    NodeList nl = envDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext dvc = new DOMValidateContext(new X509KeySelector(ks), sigElement);
    dvc.setURIDereferencer(httpUd);
    File f = new File(System.getProperty("dir.test.vector.baltimore") + System.getProperty("file.separator") + "merlin-xmldsig-twenty-three" + System.getProperty("file.separator"));
    dvc.setBaseURI(f.toURI().toString());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
    System.out.println();
}
Also used : XMLStructure(javax.xml.crypto.XMLStructure) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) URIReference(javax.xml.crypto.URIReference) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) BigInteger(java.math.BigInteger)

Example 4 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_detached_signature.

static boolean test_create_detached_signature(String canonicalizationMethod, String signatureMethod, String digestMethod, String transform, KeyInfoType keyInfo, Content contentType, int port) throws Exception {
    System.out.print("Sign ...");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    // Create SignedInfo
    DigestMethod dm = fac.newDigestMethod(digestMethod, null);
    List transformList = null;
    if (transform != null) {
        TransformParameterSpec params = null;
        switch(transform) {
            case Transform.XPATH:
                params = new XPathFilterParameterSpec("//.");
                break;
            case Transform.XPATH2:
                params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("//.", XPathType.Filter.INTERSECT)));
                break;
            case Transform.XSLT:
                Element element = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xslt.getBytes())).getDocumentElement();
                DOMStructure stylesheet = new DOMStructure(element);
                params = new XSLTTransformParameterSpec(stylesheet);
                break;
        }
        transformList = Collections.singletonList(fac.newTransform(transform, params));
    }
    String url = String.format("http://localhost:%d/%s", port, contentType);
    List refs = Collections.singletonList(fac.newReference(url, dm, transformList, null, null));
    CanonicalizationMethod cm = fac.newCanonicalizationMethod(canonicalizationMethod, (C14NMethodParameterSpec) null);
    SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
    Key signingKey;
    Key validationKey;
    switch(signatureMethod) {
        case SignatureMethod.DSA_SHA1:
        case SignatureMethod.RSA_SHA1:
            KeyPair kp = generateKeyPair(sm);
            validationKey = kp.getPublic();
            signingKey = kp.getPrivate();
            break;
        case SignatureMethod.HMAC_SHA1:
            KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
            signingKey = kg.generateKey();
            validationKey = signingKey;
            break;
        default:
            throw new RuntimeException("Unsupported signature algorithm");
    }
    SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
    // Create KeyInfo
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List list = null;
    if (keyInfo == KeyInfoType.KeyValue) {
        if (validationKey instanceof PublicKey) {
            KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
            list = Collections.singletonList(kv);
        }
    } else if (keyInfo == KeyInfoType.x509data) {
        list = Collections.singletonList(kif.newX509Data(Collections.singletonList("cn=Test")));
    } else if (keyInfo == KeyInfoType.KeyName) {
        list = Collections.singletonList(kif.newKeyName("Test"));
    } else {
        throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
    }
    KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
    // Create an empty doc for detached signature
    Document doc = dbf.newDocumentBuilder().newDocument();
    DOMSignContext xsc = new DOMSignContext(signingKey, doc);
    // Generate signature
    XMLSignature signature = fac.newXMLSignature(si, ki);
    signature.sign(xsc);
    // Save signature
    String signatureString;
    try (StringWriter writer = new StringWriter()) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        Node parent = xsc.getParent();
        trans.transform(new DOMSource(parent), new StreamResult(writer));
        signatureString = writer.toString();
    }
    System.out.print("Validate ... ");
    try (ByteArrayInputStream bis = new ByteArrayInputStream(signatureString.getBytes())) {
        doc = dbf.newDocumentBuilder().parse(bis);
    }
    NodeList nodeLst = doc.getElementsByTagName("Signature");
    Node node = nodeLst.item(0);
    if (node == null) {
        throw new RuntimeException("Couldn't find Signature element");
    }
    if (!(node instanceof Element)) {
        throw new RuntimeException("Unexpected node type");
    }
    Element sig = (Element) node;
    // Validate signature
    DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
    signature = fac.unmarshalXMLSignature(vc);
    boolean success = signature.validate(vc);
    if (!success) {
        System.out.println("Core signature validation failed");
        return false;
    }
    success = signature.getSignatureValue().validate(vc);
    if (!success) {
        System.out.println("Cryptographic validation of signature failed");
        return false;
    }
    return true;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) KeyGenerator(javax.crypto.KeyGenerator) KeyPair(java.security.KeyPair) StreamResult(javax.xml.transform.stream.StreamResult) PublicKey(java.security.PublicKey) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Example 5 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_signature_enveloped_dsa.

static void test_create_signature_enveloped_dsa(int size) throws Exception {
    System.out.println("* Generating signature-enveloped-dsa-" + size + ".xml");
    SignatureMethod sm = null;
    KeyInfo ki = null;
    Key privKey;
    if (size == 1024) {
        sm = dsaSha1;
        ki = dsa1024;
        privKey = signingKey;
    } else if (size == 2048) {
        sm = dsaSha256;
        ki = dsa2048;
        privKey = getPrivateKey("DSA", 2048);
    } else
        throw new RuntimeException("unsupported keysize:" + size);
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(fac.newReference("", sha1, Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null)));
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki);
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);
    DOMSignContext dsc = new DOMSignContext(privKey, envelope);
    sig.sign(dsc);
    //        StringWriter sw = new StringWriter();
    //        dumpDocument(doc, sw);
    //        System.out.println(sw.toString());
    DOMValidateContext dvc = new DOMValidateContext(kvks, envelope.getFirstChild());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
    System.out.println();
}
Also used : DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)18 DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 URIReference (javax.xml.crypto.URIReference)8 URIReferenceException (javax.xml.crypto.URIReferenceException)8 XMLStructure (javax.xml.crypto.XMLStructure)6 SignedInfo (javax.xml.crypto.dsig.SignedInfo)5 Key (java.security.Key)4 Reference (javax.xml.crypto.dsig.Reference)4 XMLSignature (javax.xml.crypto.dsig.XMLSignature)4 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)4 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)4 Node (org.w3c.dom.Node)4 ArrayList (java.util.ArrayList)3 GeneralSecurityException (java.security.GeneralSecurityException)2 InvalidKeyException (java.security.InvalidKeyException)2 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2 Map (java.util.Map)2 SecretKey (javax.crypto.SecretKey)2