1/*
2 * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/**
25 * @test
26 * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349 8046949
27 *      8046724 8079693
28 * @summary Basic unit tests for generating XML Signatures with JSR 105
29 * @modules java.base/sun.security.util
30 *          java.base/sun.security.x509
31 *          java.xml.crypto/org.jcp.xml.dsig.internal.dom
32 *          jdk.httpserver/com.sun.net.httpserver
33 * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
34 *     X509KeySelector.java GenerationTests.java
35 * @run main/othervm GenerationTests
36 * @author Sean Mullan
37 */
38
39import com.sun.net.httpserver.HttpExchange;
40import com.sun.net.httpserver.HttpHandler;
41import com.sun.net.httpserver.HttpServer;
42import java.io.*;
43import java.math.BigInteger;
44import java.net.InetSocketAddress;
45import java.security.Key;
46import java.security.KeyFactory;
47import java.security.KeyPair;
48import java.security.KeyPairGenerator;
49import java.security.KeyStore;
50import java.security.NoSuchAlgorithmException;
51import java.security.PrivateKey;
52import java.security.PublicKey;
53import java.security.SecureRandom;
54import java.security.cert.Certificate;
55import java.security.cert.CertificateFactory;
56import java.security.cert.X509CRL;
57import java.security.spec.KeySpec;
58import java.security.spec.DSAPrivateKeySpec;
59import java.security.spec.DSAPublicKeySpec;
60import java.security.spec.ECField;
61import java.security.spec.ECFieldFp;
62import java.security.spec.ECParameterSpec;
63import java.security.spec.ECPoint;
64import java.security.spec.ECPrivateKeySpec;
65import java.security.spec.ECPublicKeySpec;
66import java.security.spec.EllipticCurve;
67import java.security.spec.RSAPrivateKeySpec;
68import java.security.spec.RSAPublicKeySpec;
69import java.util.*;
70import javax.crypto.KeyGenerator;
71import javax.crypto.SecretKey;
72import javax.xml.XMLConstants;
73import javax.xml.parsers.*;
74import javax.xml.crypto.Data;
75import javax.xml.crypto.KeySelector;
76import javax.xml.crypto.OctetStreamData;
77import javax.xml.crypto.URIDereferencer;
78import javax.xml.crypto.URIReference;
79import javax.xml.crypto.URIReferenceException;
80import javax.xml.crypto.XMLCryptoContext;
81import javax.xml.crypto.XMLStructure;
82import javax.xml.crypto.dsig.*;
83import javax.xml.crypto.dom.*;
84import javax.xml.crypto.dsig.dom.DOMSignContext;
85import javax.xml.crypto.dsig.dom.DOMValidateContext;
86import javax.xml.crypto.dsig.keyinfo.*;
87import javax.xml.crypto.dsig.spec.*;
88import javax.xml.transform.*;
89import javax.xml.transform.dom.DOMSource;
90import javax.xml.transform.stream.StreamResult;
91import org.w3c.dom.*;
92
93/**
94 * Test that recreates merlin-xmldsig-twenty-three test vectors but with
95 * different keys and X.509 data.
96 */
97public class GenerationTests {
98
99    private static XMLSignatureFactory fac;
100    private static KeyInfoFactory kifac;
101    private static DocumentBuilder db;
102    private static CanonicalizationMethod withoutComments;
103    private static SignatureMethod dsaSha1, dsaSha256, rsaSha1,
104                                   rsaSha256, rsaSha384, rsaSha512,
105                                   ecdsaSha1;
106    private static DigestMethod sha1, sha256, sha384, sha512;
107    private static KeyInfo dsa1024, dsa2048, rsa, rsa1024,
108                           p256ki, p384ki, p521ki;
109    private static KeySelector kvks = new KeySelectors.KeyValueKeySelector();
110    private static KeySelector sks;
111    private static Key signingKey;
112    private static PublicKey validatingKey;
113    private static Certificate signingCert;
114    private static KeyStore ks;
115    private final static String DIR = System.getProperty("test.src", ".");
116//    private final static String DIR = ".";
117    private final static String DATA_DIR =
118        DIR + System.getProperty("file.separator") + "data";
119    private final static String KEYSTORE =
120        DATA_DIR + System.getProperty("file.separator") + "certs" +
121        System.getProperty("file.separator") + "test.jks";
122    private final static String CRL =
123        DATA_DIR + System.getProperty("file.separator") + "certs" +
124        System.getProperty("file.separator") + "crl";
125    private final static String ENVELOPE =
126        DATA_DIR + System.getProperty("file.separator") + "envelope.xml";
127    private static URIDereferencer httpUd = null;
128    private final static String STYLESHEET =
129        "http://www.w3.org/TR/xml-stylesheet";
130    private final static String STYLESHEET_B64 =
131        "http://www.w3.org/Signature/2002/04/xml-stylesheet.b64";
132    private final static String DSA_SHA256 =
133        "http://www.w3.org/2009/xmldsig11#dsa-sha256";
134
135    private static final String BOGUS = "bogus";
136
137    private static final  String xslt = ""
138          + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'\n"
139          + "            xmlns='http://www.w3.org/TR/xhtml1/strict' \n"
140          + "            exclude-result-prefixes='foo' \n"
141          + "            version='1.0'>\n"
142          + "  <xsl:output encoding='UTF-8' \n"
143          + "           indent='no' \n"
144          + "           method='xml' />\n"
145          + "  <xsl:template match='/'>\n"
146          + "    <html>\n"
147          + "   <head>\n"
148          + "    <title>Notaries</title>\n"
149          + "   </head>\n"
150          + "   <body>\n"
151          + "    <table>\n"
152          + "      <xsl:for-each select='Notaries/Notary'>\n"
153          + "           <tr>\n"
154          + "           <th>\n"
155          + "            <xsl:value-of select='@name' />\n"
156          + "           </th>\n"
157          + "           </tr>\n"
158          + "      </xsl:for-each>\n"
159          + "    </table>\n"
160          + "   </body>\n"
161          + "    </html>\n"
162          + "  </xsl:template>\n"
163          + "</xsl:stylesheet>\n";
164
165    private static final String[] canonicalizationMethods = new String[] {
166        CanonicalizationMethod.EXCLUSIVE,
167        CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
168        CanonicalizationMethod.INCLUSIVE,
169        CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS
170    };
171
172    private static final String[] xml_transforms = new String[] {
173        Transform.XSLT,
174        Transform.XPATH,
175        Transform.XPATH2,
176        CanonicalizationMethod.EXCLUSIVE,
177        CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
178        CanonicalizationMethod.INCLUSIVE,
179        CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
180    };
181
182    private static final String[] non_xml_transforms = new String[] {
183        null, Transform.BASE64
184    };
185
186    private static final String[] signatureMethods = new String[] {
187        SignatureMethod.DSA_SHA1,
188        SignatureMethod.RSA_SHA1,
189        SignatureMethod.HMAC_SHA1
190    };
191
192    private static enum Content {
193        Xml, Text, Base64, NotExisitng
194    }
195
196    private static enum KeyInfoType {
197        KeyValue, x509data, KeyName
198    }
199
200    private static boolean result = true;
201
202    public static void main(String args[]) throws Exception {
203        setup();
204        test_create_signature_enveloped_dsa(1024);
205        test_create_signature_enveloped_dsa(2048);
206        test_create_signature_enveloping_b64_dsa();
207        test_create_signature_enveloping_dsa();
208        test_create_signature_enveloping_hmac_sha1_40();
209        test_create_signature_enveloping_hmac_sha256();
210        test_create_signature_enveloping_hmac_sha384();
211        test_create_signature_enveloping_hmac_sha512();
212        test_create_signature_enveloping_rsa();
213        test_create_signature_enveloping_p256_sha1();
214        test_create_signature_enveloping_p384_sha1();
215        test_create_signature_enveloping_p521_sha1();
216        test_create_signature_external_b64_dsa();
217        test_create_signature_external_dsa();
218        test_create_signature_keyname();
219        test_create_signature_retrievalmethod_rawx509crt();
220        test_create_signature_x509_crt_crl();
221        test_create_signature_x509_crt();
222        test_create_signature_x509_is();
223        test_create_signature_x509_ski();
224        test_create_signature_x509_sn();
225        test_create_signature();
226        test_create_exc_signature();
227        test_create_sign_spec();
228        test_create_signature_enveloping_sha256_dsa();
229        test_create_signature_enveloping_sha384_rsa_sha256();
230        test_create_signature_enveloping_sha512_rsa_sha384();
231        test_create_signature_enveloping_sha512_rsa_sha512();
232        test_create_signature_reference_dependency();
233        test_create_signature_with_attr_in_no_namespace();
234        test_create_signature_with_empty_id();
235
236        // run tests for detached signatures with local http server
237        try (Http server = Http.startServer()) {
238            server.start();
239
240            // tests for XML documents
241            Arrays.stream(canonicalizationMethods).forEach(c ->
242                Arrays.stream(signatureMethods).forEach(s ->
243                    Arrays.stream(xml_transforms).forEach(t ->
244                        Arrays.stream(KeyInfoType.values()).forEach(k -> {
245                            test_create_detached_signature(c, s, t, k,
246                                    Content.Xml, server.getPort(), false, null);
247                        }))));
248
249            // tests for text data with no transform
250            Arrays.stream(canonicalizationMethods).forEach(c ->
251                Arrays.stream(signatureMethods).forEach(s ->
252                    Arrays.stream(KeyInfoType.values()).forEach(k -> {
253                        test_create_detached_signature(c, s, null, k,
254                                Content.Text, server.getPort(), false, null);
255                    })));
256
257            // tests for base64 data
258            Arrays.stream(canonicalizationMethods).forEach(c ->
259                Arrays.stream(signatureMethods).forEach(s ->
260                    Arrays.stream(non_xml_transforms).forEach(t ->
261                        Arrays.stream(KeyInfoType.values()).forEach(k -> {
262                            test_create_detached_signature(c, s, t, k,
263                                    Content.Base64, server.getPort(),
264                                    false, null);
265                        }))));
266
267            // negative tests
268
269            // unknown CanonicalizationMethod
270            test_create_detached_signature(
271                    CanonicalizationMethod.EXCLUSIVE + BOGUS,
272                    SignatureMethod.DSA_SHA1,
273                    CanonicalizationMethod.INCLUSIVE,
274                    KeyInfoType.KeyName,
275                    Content.Xml,
276                    server.getPort(),
277                    true,
278                    NoSuchAlgorithmException.class);
279
280            // unknown SignatureMethod
281            test_create_detached_signature(
282                    CanonicalizationMethod.EXCLUSIVE,
283                    SignatureMethod.DSA_SHA1 + BOGUS,
284                    CanonicalizationMethod.INCLUSIVE,
285                    KeyInfoType.KeyName, Content.Xml,
286                    server.getPort(),
287                    true,
288                    NoSuchAlgorithmException.class);
289
290            // unknown Transform
291            test_create_detached_signature(
292                    CanonicalizationMethod.EXCLUSIVE,
293                    SignatureMethod.DSA_SHA1,
294                    CanonicalizationMethod.INCLUSIVE + BOGUS,
295                    KeyInfoType.KeyName, Content.Xml,
296                    server.getPort(),
297                    true,
298                    NoSuchAlgorithmException.class);
299
300            // no source document
301            test_create_detached_signature(
302                    CanonicalizationMethod.EXCLUSIVE,
303                    SignatureMethod.DSA_SHA1,
304                    CanonicalizationMethod.INCLUSIVE,
305                    KeyInfoType.KeyName,
306                    Content.NotExisitng,
307                    server.getPort(),
308                    true,
309                    XMLSignatureException.class);
310
311            // wrong transform for text data
312            test_create_detached_signature(
313                    CanonicalizationMethod.EXCLUSIVE,
314                    SignatureMethod.DSA_SHA1,
315                    CanonicalizationMethod.INCLUSIVE,
316                    KeyInfoType.KeyName,
317                    Content.Text,
318                    server.getPort(),
319                    true,
320                    XMLSignatureException.class);
321        }
322
323        if (!result) {
324            throw new RuntimeException("At least one test case failed");
325        }
326    }
327
328    private static void setup() throws Exception {
329        fac = XMLSignatureFactory.getInstance();
330        kifac = fac.getKeyInfoFactory();
331        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
332        dbf.setNamespaceAware(true);
333        db = dbf.newDocumentBuilder();
334
335        // get key & self-signed certificate from keystore
336        FileInputStream fis = new FileInputStream(KEYSTORE);
337        ks = KeyStore.getInstance("JKS");
338        ks.load(fis, "changeit".toCharArray());
339        signingKey = ks.getKey("user", "changeit".toCharArray());
340        signingCert = ks.getCertificate("user");
341        validatingKey = signingCert.getPublicKey();
342
343        // create common objects
344        withoutComments = fac.newCanonicalizationMethod
345            (CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null);
346        dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
347        dsaSha256 = fac.newSignatureMethod(DSA_SHA256, null);
348        sha1 = fac.newDigestMethod(DigestMethod.SHA1, null);
349        sha256 = fac.newDigestMethod(DigestMethod.SHA256, null);
350        sha384 = fac.newDigestMethod
351            ("http://www.w3.org/2001/04/xmldsig-more#sha384", null);
352        sha512 = fac.newDigestMethod(DigestMethod.SHA512, null);
353        dsa1024 = kifac.newKeyInfo(Collections.singletonList
354            (kifac.newKeyValue(validatingKey)));
355        dsa2048 = kifac.newKeyInfo(Collections.singletonList
356            (kifac.newKeyValue(getPublicKey("DSA", 2048))));
357        rsa = kifac.newKeyInfo(Collections.singletonList
358            (kifac.newKeyValue(getPublicKey("RSA", 512))));
359        rsa1024 = kifac.newKeyInfo(Collections.singletonList
360            (kifac.newKeyValue(getPublicKey("RSA", 1024))));
361        p256ki = kifac.newKeyInfo(Collections.singletonList
362            (kifac.newKeyValue(getECPublicKey("P256"))));
363        p384ki = kifac.newKeyInfo(Collections.singletonList
364            (kifac.newKeyValue(getECPublicKey("P384"))));
365        p521ki = kifac.newKeyInfo(Collections.singletonList
366            (kifac.newKeyValue(getECPublicKey("P521"))));
367        rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
368        rsaSha256 = fac.newSignatureMethod
369            ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null);
370        rsaSha384 = fac.newSignatureMethod
371            ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384", null);
372        rsaSha512 = fac.newSignatureMethod
373            ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512", null);
374        ecdsaSha1 = fac.newSignatureMethod
375            ("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1", null);
376        sks = new KeySelectors.SecretKeySelector("secret".getBytes("ASCII"));
377
378        httpUd = new HttpURIDereferencer();
379    }
380
381    static void test_create_signature_enveloped_dsa(int size) throws Exception {
382        System.out.println("* Generating signature-enveloped-dsa-"
383                           + size + ".xml");
384        SignatureMethod sm = null;
385        KeyInfo ki = null;
386        Key privKey;
387        if (size == 1024) {
388            sm = dsaSha1;
389            ki = dsa1024;
390            privKey = signingKey;
391        } else if (size == 2048) {
392            sm = dsaSha256;
393            ki = dsa2048;
394            privKey = getPrivateKey("DSA", 2048);
395        } else throw new RuntimeException("unsupported keysize:" + size);
396
397        // create SignedInfo
398        SignedInfo si = fac.newSignedInfo
399            (withoutComments, sm, Collections.singletonList
400                (fac.newReference
401                    ("", sha1, Collections.singletonList
402                        (fac.newTransform(Transform.ENVELOPED,
403                            (TransformParameterSpec) null)),
404                 null, null)));
405
406        // create XMLSignature
407        XMLSignature sig = fac.newXMLSignature(si, ki);
408
409        Document doc = db.newDocument();
410        Element envelope = doc.createElementNS
411            ("http://example.org/envelope", "Envelope");
412        envelope.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
413            "xmlns", "http://example.org/envelope");
414        doc.appendChild(envelope);
415
416        DOMSignContext dsc = new DOMSignContext(privKey, envelope);
417
418        sig.sign(dsc);
419//        StringWriter sw = new StringWriter();
420//        dumpDocument(doc, sw);
421//        System.out.println(sw.toString());
422
423        DOMValidateContext dvc = new DOMValidateContext
424            (kvks, envelope.getFirstChild());
425        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
426
427        if (sig.equals(sig2) == false) {
428            throw new Exception
429                ("Unmarshalled signature is not equal to generated signature");
430        }
431
432        if (sig2.validate(dvc) == false) {
433            throw new Exception("Validation of generated signature failed");
434        }
435        System.out.println();
436    }
437
438    static void test_create_signature_enveloping_b64_dsa() throws Exception {
439        System.out.println("* Generating signature-enveloping-b64-dsa.xml");
440        test_create_signature_enveloping
441            (sha1, dsaSha1, dsa1024, signingKey, kvks, true);
442        System.out.println();
443    }
444
445    static void test_create_signature_enveloping_dsa() throws Exception {
446        System.out.println("* Generating signature-enveloping-dsa.xml");
447        test_create_signature_enveloping
448            (sha1, dsaSha1, dsa1024, signingKey, kvks, false);
449        System.out.println();
450    }
451
452    static void test_create_signature_enveloping_sha256_dsa() throws Exception {
453        System.out.println("* Generating signature-enveloping-sha256-dsa.xml");
454        test_create_signature_enveloping
455            (sha256, dsaSha1, dsa1024, signingKey, kvks, false);
456        System.out.println();
457    }
458
459    static void test_create_signature_enveloping_hmac_sha1_40()
460        throws Exception {
461        System.out.println("* Generating signature-enveloping-hmac-sha1-40.xml");
462        SignatureMethod hmacSha1 = fac.newSignatureMethod
463            (SignatureMethod.HMAC_SHA1, new HMACParameterSpec(40));
464        try {
465            test_create_signature_enveloping(sha1, hmacSha1, null,
466                getSecretKey("secret".getBytes("ASCII")), sks, false);
467        } catch (Exception e) {
468            if (!(e instanceof XMLSignatureException)) {
469                throw e;
470            }
471        }
472        System.out.println();
473    }
474
475    static void test_create_signature_enveloping_hmac_sha256()
476        throws Exception {
477        System.out.println("* Generating signature-enveloping-hmac-sha256.xml");
478        SignatureMethod hmacSha256 = fac.newSignatureMethod
479            ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", null);
480        test_create_signature_enveloping(sha1, hmacSha256, null,
481            getSecretKey("secret".getBytes("ASCII")), sks, false);
482        System.out.println();
483    }
484
485    static void test_create_signature_enveloping_hmac_sha384()
486        throws Exception {
487        System.out.println("* Generating signature-enveloping-hmac-sha384.xml");
488        SignatureMethod hmacSha384 = fac.newSignatureMethod
489            ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", null);
490        test_create_signature_enveloping(sha1, hmacSha384, null,
491            getSecretKey("secret".getBytes("ASCII")), sks, false);
492        System.out.println();
493    }
494
495    static void test_create_signature_enveloping_hmac_sha512()
496        throws Exception {
497        System.out.println("* Generating signature-enveloping-hmac-sha512.xml");
498        SignatureMethod hmacSha512 = fac.newSignatureMethod
499            ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", null);
500        test_create_signature_enveloping(sha1, hmacSha512, null,
501            getSecretKey("secret".getBytes("ASCII")), sks, false);
502        System.out.println();
503    }
504
505    static void test_create_signature_enveloping_rsa() throws Exception {
506        System.out.println("* Generating signature-enveloping-rsa.xml");
507        test_create_signature_enveloping(sha1, rsaSha1, rsa,
508            getPrivateKey("RSA", 512), kvks, false);
509        System.out.println();
510    }
511
512    static void test_create_signature_enveloping_sha384_rsa_sha256()
513        throws Exception {
514        System.out.println("* Generating signature-enveloping-sha384-rsa_sha256.xml");
515        test_create_signature_enveloping(sha384, rsaSha256, rsa,
516            getPrivateKey("RSA", 512), kvks, false);
517        System.out.println();
518    }
519
520    static void test_create_signature_enveloping_sha512_rsa_sha384()
521        throws Exception {
522        System.out.println("* Generating signature-enveloping-sha512-rsa_sha384.xml");
523        test_create_signature_enveloping(sha512, rsaSha384, rsa1024,
524            getPrivateKey("RSA", 1024), kvks, false);
525        System.out.println();
526    }
527
528    static void test_create_signature_enveloping_sha512_rsa_sha512()
529        throws Exception {
530        System.out.println("* Generating signature-enveloping-sha512-rsa_sha512.xml");
531        test_create_signature_enveloping(sha512, rsaSha512, rsa1024,
532            getPrivateKey("RSA", 1024), kvks, false);
533        System.out.println();
534    }
535
536    static void test_create_signature_enveloping_p256_sha1() throws Exception {
537        System.out.println("* Generating signature-enveloping-p256-sha1.xml");
538        test_create_signature_enveloping(sha1, ecdsaSha1, p256ki,
539            getECPrivateKey("P256"), kvks, false);
540        System.out.println();
541    }
542
543    static void test_create_signature_enveloping_p384_sha1() throws Exception {
544        System.out.println("* Generating signature-enveloping-p384-sha1.xml");
545        test_create_signature_enveloping(sha1, ecdsaSha1, p384ki,
546            getECPrivateKey("P384"), kvks, false);
547        System.out.println();
548    }
549
550    static void test_create_signature_enveloping_p521_sha1() throws Exception {
551        System.out.println("* Generating signature-enveloping-p521-sha1.xml");
552        test_create_signature_enveloping(sha1, ecdsaSha1, p521ki,
553            getECPrivateKey("P521"), kvks, false);
554        System.out.println();
555    }
556
557    static void test_create_signature_external_b64_dsa() throws Exception {
558        System.out.println("* Generating signature-external-b64-dsa.xml");
559        test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, true);
560        System.out.println();
561    }
562
563    static void test_create_signature_external_dsa() throws Exception {
564        System.out.println("* Generating signature-external-dsa.xml");
565        test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, false);
566        System.out.println();
567    }
568
569    static void test_create_signature_keyname() throws Exception {
570        System.out.println("* Generating signature-keyname.xml");
571        KeyInfo kn = kifac.newKeyInfo(Collections.singletonList
572            (kifac.newKeyName("user")));
573        test_create_signature_external(dsaSha1, kn, signingKey,
574            new X509KeySelector(ks), false);
575        System.out.println();
576    }
577
578    static void test_create_signature_retrievalmethod_rawx509crt()
579        throws Exception {
580        System.out.println(
581            "* Generating signature-retrievalmethod-rawx509crt.xml");
582        KeyInfo rm = kifac.newKeyInfo(Collections.singletonList
583            (kifac.newRetrievalMethod
584            ("certs/user.crt", X509Data.RAW_X509_CERTIFICATE_TYPE, null)));
585        test_create_signature_external(dsaSha1, rm, signingKey,
586            new X509KeySelector(ks), false);
587        System.out.println();
588    }
589
590    static void test_create_signature_x509_crt_crl() throws Exception {
591        System.out.println("* Generating signature-x509-crt-crl.xml");
592        List<Object> xds = new ArrayList<>();
593        CertificateFactory cf = CertificateFactory.getInstance("X.509");
594        xds.add(signingCert);
595        FileInputStream fis = new FileInputStream(CRL);
596        X509CRL crl = (X509CRL) cf.generateCRL(fis);
597        fis.close();
598        xds.add(crl);
599        KeyInfo crt_crl = kifac.newKeyInfo(Collections.singletonList
600            (kifac.newX509Data(xds)));
601
602        test_create_signature_external(dsaSha1, crt_crl, signingKey,
603            new X509KeySelector(ks), false);
604        System.out.println();
605    }
606
607    static void test_create_signature_x509_crt() throws Exception {
608        System.out.println("* Generating signature-x509-crt.xml");
609        KeyInfo crt = kifac.newKeyInfo(Collections.singletonList
610            (kifac.newX509Data(Collections.singletonList(signingCert))));
611
612        test_create_signature_external(dsaSha1, crt, signingKey,
613            new X509KeySelector(ks), false);
614        System.out.println();
615    }
616
617    static void test_create_signature_x509_is() throws Exception {
618        System.out.println("* Generating signature-x509-is.xml");
619        KeyInfo is = kifac.newKeyInfo(Collections.singletonList
620            (kifac.newX509Data(Collections.singletonList
621            (kifac.newX509IssuerSerial
622            ("CN=User", new BigInteger("45ef2729", 16))))));
623        test_create_signature_external(dsaSha1, is, signingKey,
624            new X509KeySelector(ks), false);
625        System.out.println();
626    }
627
628    static void test_create_signature_x509_ski() throws Exception {
629        System.out.println("* Generating signature-x509-ski.xml");
630        KeyInfo ski = kifac.newKeyInfo(Collections.singletonList
631            (kifac.newX509Data(Collections.singletonList
632            ("keyid".getBytes("ASCII")))));
633
634        test_create_signature_external(dsaSha1, ski, signingKey,
635            KeySelector.singletonKeySelector(validatingKey), false);
636        System.out.println();
637    }
638
639    static void test_create_signature_x509_sn() throws Exception {
640        System.out.println("* Generating signature-x509-sn.xml");
641        KeyInfo sn = kifac.newKeyInfo(Collections.singletonList
642            (kifac.newX509Data(Collections.singletonList("CN=User"))));
643
644        test_create_signature_external(dsaSha1, sn, signingKey,
645            new X509KeySelector(ks), false);
646        System.out.println();
647    }
648
649    static void test_create_signature_reference_dependency() throws Exception {
650        System.out.println("* Generating signature-reference-dependency.xml");
651        // create references
652        List<Reference> refs = Collections.singletonList
653            (fac.newReference("#object-1", sha1));
654
655        // create SignedInfo
656        SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
657
658        // create objects
659        List<XMLObject> objs = new ArrayList<>();
660
661        // Object 1
662        List<Reference> manRefs = Collections.singletonList
663            (fac.newReference("#object-2", sha1));
664        objs.add(fac.newXMLObject(Collections.singletonList
665            (fac.newManifest(manRefs, "manifest-1")), "object-1", null, null));
666
667        // Object 2
668        Document doc = db.newDocument();
669        Element nc = doc.createElementNS(null, "NonCommentandus");
670        nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");
671        nc.appendChild(doc.createComment(" Commentandum "));
672        objs.add(fac.newXMLObject(Collections.singletonList
673            (new DOMStructure(nc)), "object-2", null, null));
674
675        // create XMLSignature
676        XMLSignature sig = fac.newXMLSignature(si, rsa, objs, "signature", null);
677        DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
678
679        sig.sign(dsc);
680
681//      dumpDocument(doc, new PrintWriter(System.out));
682
683        DOMValidateContext dvc = new DOMValidateContext
684            (kvks, doc.getDocumentElement());
685        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
686
687        if (sig.equals(sig2) == false) {
688            throw new Exception
689                ("Unmarshalled signature is not equal to generated signature");
690        }
691        if (sig2.validate(dvc) == false) {
692            throw new Exception("Validation of generated signature failed");
693        }
694
695        System.out.println();
696    }
697
698    static void test_create_signature_with_attr_in_no_namespace()
699        throws Exception
700    {
701        System.out.println
702            ("* Generating signature-with-attr-in-no-namespace.xml");
703
704        // create references
705        List<Reference> refs = Collections.singletonList
706            (fac.newReference("#unknown", sha1));
707
708        // create SignedInfo
709        SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
710
711        // create object-1
712        Document doc = db.newDocument();
713        Element nc = doc.createElementNS(null, "NonCommentandus");
714        // add attribute with no namespace
715        nc.setAttribute("Id", "unknown");
716        XMLObject obj = fac.newXMLObject(Collections.singletonList
717            (new DOMStructure(nc)), "object-1", null, null);
718
719        // create XMLSignature
720        XMLSignature sig = fac.newXMLSignature(si, rsa,
721                                               Collections.singletonList(obj),
722                                               "signature", null);
723        DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
724        dsc.setIdAttributeNS(nc, null, "Id");
725
726        sig.sign(dsc);
727
728//      dumpDocument(doc, new PrintWriter(System.out));
729
730        DOMValidateContext dvc = new DOMValidateContext
731            (kvks, doc.getDocumentElement());
732        dvc.setIdAttributeNS(nc, null, "Id");
733        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
734
735        if (sig.equals(sig2) == false) {
736            throw new Exception
737                ("Unmarshalled signature is not equal to generated signature");
738        }
739        if (sig2.validate(dvc) == false) {
740            throw new Exception("Validation of generated signature failed");
741        }
742
743        System.out.println();
744    }
745
746    static void test_create_signature_with_empty_id() throws Exception {
747        System.out.println("* Generating signature-with-empty-id.xml");
748
749        // create references
750        List<Reference> refs = Collections.singletonList
751            (fac.newReference("#", sha1));
752
753        // create SignedInfo
754        SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
755
756        // create object with empty id
757        Document doc = db.newDocument();
758        XMLObject obj = fac.newXMLObject(Collections.singletonList
759            (new DOMStructure(doc.createTextNode("I am the text."))),
760            "", "text/plain", null);
761
762        // create XMLSignature
763        XMLSignature sig = fac.newXMLSignature(si, rsa,
764                                               Collections.singletonList(obj),
765                                               "signature", null);
766        DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
767        sig.sign(dsc);
768    }
769
770    static void test_create_signature() throws Exception {
771        System.out.println("* Generating signature.xml");
772
773        // create references
774        List<Reference> refs = new ArrayList<>();
775
776        // Reference 1
777        refs.add(fac.newReference(STYLESHEET, sha1));
778
779        // Reference 2
780        refs.add(fac.newReference
781            (STYLESHEET_B64,
782            sha1, Collections.singletonList
783            (fac.newTransform(Transform.BASE64,
784                (TransformParameterSpec) null)), null, null));
785
786        // Reference 3
787        refs.add(fac.newReference("#object-1", sha1, Collections.singletonList
788            (fac.newTransform(Transform.XPATH,
789            new XPathFilterParameterSpec("self::text()"))),
790            XMLObject.TYPE, null));
791
792        // Reference 4
793        String expr = "\n"
794          + " ancestor-or-self::dsig:SignedInfo                  " + "\n"
795          + "  and                                               " + "\n"
796          + " count(ancestor-or-self::dsig:Reference |           " + "\n"
797          + "      here()/ancestor::dsig:Reference[1]) >         " + "\n"
798          + " count(ancestor-or-self::dsig:Reference)            " + "\n"
799          + "  or                                                " + "\n"
800          + " count(ancestor-or-self::node() |                   " + "\n"
801          + "      id('notaries')) =                             " + "\n"
802          + " count(ancestor-or-self::node())                    " + "\n";
803
804        XPathFilterParameterSpec xfp = new XPathFilterParameterSpec(expr,
805            Collections.singletonMap("dsig", XMLSignature.XMLNS));
806        refs.add(fac.newReference("", sha1, Collections.singletonList
807            (fac.newTransform(Transform.XPATH, xfp)),
808            XMLObject.TYPE, null));
809
810        // Reference 5
811        refs.add(fac.newReference("#object-2", sha1, Collections.singletonList
812            (fac.newTransform
813                (Transform.BASE64, (TransformParameterSpec) null)),
814            XMLObject.TYPE, null));
815
816        // Reference 6
817        refs.add(fac.newReference
818            ("#manifest-1", sha1, null, Manifest.TYPE, null));
819
820        // Reference 7
821        refs.add(fac.newReference("#signature-properties-1", sha1, null,
822            SignatureProperties.TYPE, null));
823
824        // Reference 8
825        List<Transform> transforms = new ArrayList<>();
826        transforms.add(fac.newTransform
827            (Transform.ENVELOPED, (TransformParameterSpec) null));
828        refs.add(fac.newReference("", sha1, transforms, null, null));
829
830        // Reference 9
831        transforms.add(fac.newTransform
832            (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
833                (TransformParameterSpec) null));
834        refs.add(fac.newReference("", sha1, transforms, null, null));
835
836        // Reference 10
837        Transform env = fac.newTransform
838            (Transform.ENVELOPED, (TransformParameterSpec) null);
839        refs.add(fac.newReference("#xpointer(/)",
840            sha1, Collections.singletonList(env), null, null));
841
842        // Reference 11
843        transforms.clear();
844        transforms.add(fac.newTransform
845            (Transform.ENVELOPED, (TransformParameterSpec) null));
846        transforms.add(fac.newTransform
847            (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
848             (TransformParameterSpec) null));
849        refs.add(fac.newReference("#xpointer(/)", sha1, transforms,
850            null, null));
851
852        // Reference 12
853        refs.add
854            (fac.newReference("#object-3", sha1, null, XMLObject.TYPE, null));
855
856        // Reference 13
857        Transform withComments = fac.newTransform
858            (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
859             (TransformParameterSpec) null);
860        refs.add(fac.newReference("#object-3", sha1,
861            Collections.singletonList(withComments), XMLObject.TYPE, null));
862
863        // Reference 14
864        refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, null,
865            XMLObject.TYPE, null));
866
867        // Reference 15
868        withComments = fac.newTransform
869            (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
870             (TransformParameterSpec) null);
871        refs.add(fac.newReference("#xpointer(id('object-3'))", sha1,
872            Collections.singletonList(withComments), XMLObject.TYPE, null));
873
874        // Reference 16
875        refs.add(fac.newReference("#reference-2", sha1));
876
877        // Reference 17
878        refs.add(fac.newReference("#manifest-reference-1", sha1, null,
879            null, "reference-1"));
880
881        // Reference 18
882        refs.add(fac.newReference("#reference-1", sha1, null, null,
883            "reference-2"));
884
885        // create SignedInfo
886        SignedInfo si = fac.newSignedInfo(withoutComments, dsaSha1, refs);
887
888        // create keyinfo
889        XPathFilterParameterSpec xpf = new XPathFilterParameterSpec(
890            "ancestor-or-self::dsig:X509Data",
891            Collections.singletonMap("dsig", XMLSignature.XMLNS));
892        RetrievalMethod rm = kifac.newRetrievalMethod("#object-4",
893            X509Data.TYPE, Collections.singletonList(fac.newTransform
894            (Transform.XPATH, xpf)));
895        KeyInfo ki = kifac.newKeyInfo(Collections.singletonList(rm), null);
896
897        Document doc = db.newDocument();
898
899        // create objects
900        List<XMLObject> objs = new ArrayList<>();
901
902        // Object 1
903        objs.add(fac.newXMLObject(Collections.singletonList
904            (new DOMStructure(doc.createTextNode("I am the text."))),
905            "object-1", "text/plain", null));
906
907        // Object 2
908        objs.add(fac.newXMLObject(Collections.singletonList
909            (new DOMStructure(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="))),
910            "object-2", "text/plain", Transform.BASE64));
911
912        // Object 3
913        Element nc = doc.createElementNS(null, "NonCommentandus");
914        nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");
915        nc.appendChild(doc.createComment(" Commentandum "));
916        objs.add(fac.newXMLObject(Collections.singletonList
917            (new DOMStructure(nc)), "object-3", null, null));
918
919        // Manifest
920        List<Reference> manRefs = new ArrayList<>();
921
922        // Manifest Reference 1
923        manRefs.add(fac.newReference(STYLESHEET,
924            sha1, null, null, "manifest-reference-1"));
925
926        // Manifest Reference 2
927        manRefs.add(fac.newReference("#reference-1", sha1));
928
929        // Manifest Reference 3
930        List<Transform> manTrans = new ArrayList<>();
931        Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));
932        Node xslElem = docxslt.getDocumentElement();
933
934        manTrans.add(fac.newTransform(Transform.XSLT,
935            new XSLTTransformParameterSpec(new DOMStructure(xslElem))));
936        manTrans.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE,
937            (TransformParameterSpec) null));
938        manRefs.add(fac.newReference("#notaries", sha1, manTrans, null, null));
939
940        objs.add(fac.newXMLObject(Collections.singletonList
941            (fac.newManifest(manRefs, "manifest-1")), null, null, null));
942
943        // SignatureProperties
944        Element sa = doc.createElementNS("urn:demo", "SignerAddress");
945        sa.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:demo");
946        Element ip = doc.createElementNS("urn:demo", "IP");
947        ip.appendChild(doc.createTextNode("192.168.21.138"));
948        sa.appendChild(ip);
949        SignatureProperty sp = fac.newSignatureProperty
950            (Collections.singletonList(new DOMStructure(sa)),
951            "#signature", null);
952        SignatureProperties sps = fac.newSignatureProperties
953            (Collections.singletonList(sp), "signature-properties-1");
954        objs.add(fac.newXMLObject(Collections.singletonList(sps), null,
955            null, null));
956
957        // Object 4
958        List<Object> xds = new ArrayList<>();
959        xds.add("CN=User");
960        xds.add(kifac.newX509IssuerSerial
961            ("CN=User", new BigInteger("45ef2729", 16)));
962        xds.add(signingCert);
963        objs.add(fac.newXMLObject(Collections.singletonList
964            (kifac.newX509Data(xds)), "object-4", null, null));
965
966        // create XMLSignature
967        XMLSignature sig = fac.newXMLSignature(si, ki, objs, "signature", null);
968
969        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
970        dbf.setNamespaceAware(true);
971        dbf.setValidating(false);
972        Document envDoc = dbf.newDocumentBuilder().parse
973            (new FileInputStream(ENVELOPE));
974        Element ys = (Element)
975            envDoc.getElementsByTagName("YoursSincerely").item(0);
976
977        DOMSignContext dsc = new DOMSignContext(signingKey, ys);
978        dsc.setURIDereferencer(httpUd);
979
980        sig.sign(dsc);
981
982//      StringWriter sw = new StringWriter();
983//        dumpDocument(envDoc, sw);
984
985        NodeList nl =
986            envDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
987        if (nl.getLength() == 0) {
988            throw new Exception("Couldn't find signature Element");
989        }
990        Element sigElement = (Element) nl.item(0);
991
992        DOMValidateContext dvc = new DOMValidateContext
993            (new X509KeySelector(ks), sigElement);
994        dvc.setURIDereferencer(httpUd);
995        File f = new File(
996            System.getProperty("dir.test.vector.baltimore") +
997            System.getProperty("file.separator") +
998            "merlin-xmldsig-twenty-three" +
999            System.getProperty("file.separator"));
1000        dvc.setBaseURI(f.toURI().toString());
1001
1002        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1003
1004        if (sig.equals(sig2) == false) {
1005            throw new Exception
1006                ("Unmarshalled signature is not equal to generated signature");
1007        }
1008        if (sig2.validate(dvc) == false) {
1009            throw new Exception("Validation of generated signature failed");
1010        }
1011        System.out.println();
1012    }
1013
1014    private static void dumpDocument(Document doc, Writer w) throws Exception {
1015        TransformerFactory tf = TransformerFactory.newInstance();
1016        Transformer trans = tf.newTransformer();
1017//      trans.setOutputProperty(OutputKeys.INDENT, "yes");
1018        trans.transform(new DOMSource(doc), new StreamResult(w));
1019    }
1020
1021    private static void test_create_signature_external
1022        (SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks,
1023        boolean b64) throws Exception {
1024
1025        // create reference
1026        Reference ref;
1027        if (b64) {
1028            ref = fac.newReference
1029                (STYLESHEET_B64,
1030                sha1, Collections.singletonList
1031                (fac.newTransform(Transform.BASE64,
1032                 (TransformParameterSpec) null)), null, null);
1033        } else {
1034            ref = fac.newReference(STYLESHEET, sha1);
1035        }
1036
1037        // create SignedInfo
1038        SignedInfo si = fac.newSignedInfo(withoutComments, sm,
1039            Collections.singletonList(ref));
1040
1041        Document doc = db.newDocument();
1042
1043        // create XMLSignature
1044        XMLSignature sig = fac.newXMLSignature(si, ki);
1045
1046        DOMSignContext dsc = new DOMSignContext(signingKey, doc);
1047        dsc.setURIDereferencer(httpUd);
1048
1049        sig.sign(dsc);
1050
1051        DOMValidateContext dvc = new DOMValidateContext
1052            (ks, doc.getDocumentElement());
1053        File f = new File(DATA_DIR);
1054        dvc.setBaseURI(f.toURI().toString());
1055        dvc.setURIDereferencer(httpUd);
1056
1057        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1058
1059        if (sig.equals(sig2) == false) {
1060            throw new Exception
1061                ("Unmarshalled signature is not equal to generated signature");
1062        }
1063        if (sig2.validate(dvc) == false) {
1064            throw new Exception("Validation of generated signature failed");
1065        }
1066    }
1067
1068    private static void test_create_signature_enveloping
1069        (DigestMethod dm, SignatureMethod sm, KeyInfo ki, Key signingKey,
1070         KeySelector ks, boolean b64) throws Exception {
1071
1072        // create reference
1073        Reference ref;
1074        if (b64) {
1075            ref = fac.newReference("#object", dm, Collections.singletonList
1076                (fac.newTransform(Transform.BASE64,
1077                 (TransformParameterSpec) null)), null, null);
1078        } else {
1079            ref = fac.newReference("#object", dm);
1080        }
1081
1082        // create SignedInfo
1083        SignedInfo si = fac.newSignedInfo(withoutComments, sm,
1084            Collections.singletonList(ref));
1085
1086        Document doc = db.newDocument();
1087        // create Objects
1088        String text = b64 ? "c29tZSB0ZXh0" : "some text";
1089        XMLObject obj = fac.newXMLObject(Collections.singletonList
1090            (new DOMStructure(doc.createTextNode(text))),
1091            "object", null, null);
1092
1093        // create XMLSignature
1094        XMLSignature sig = fac.newXMLSignature
1095            (si, ki, Collections.singletonList(obj), null, null);
1096
1097        DOMSignContext dsc = new DOMSignContext(signingKey, doc);
1098
1099        sig.sign(dsc);
1100
1101//        dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1102
1103        DOMValidateContext dvc = new DOMValidateContext
1104            (ks, doc.getDocumentElement());
1105        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1106
1107        if (sig.equals(sig2) == false) {
1108            throw new Exception
1109                ("Unmarshalled signature is not equal to generated signature");
1110        }
1111        if (sig2.validate(dvc) == false) {
1112            throw new Exception("Validation of generated signature failed");
1113        }
1114    }
1115
1116    static void test_create_exc_signature() throws Exception {
1117        System.out.println("* Generating exc_signature.xml");
1118        List<Reference> refs = new ArrayList<>(4);
1119
1120        // create reference 1
1121        refs.add(fac.newReference
1122            ("#xpointer(id('to-be-signed'))",
1123             fac.newDigestMethod(DigestMethod.SHA1, null),
1124             Collections.singletonList
1125                (fac.newTransform(CanonicalizationMethod.EXCLUSIVE,
1126                 (TransformParameterSpec) null)),
1127             null, null));
1128
1129        // create reference 2
1130        List<String> prefixList = new ArrayList<>(2);
1131        prefixList.add("bar");
1132        prefixList.add("#default");
1133        ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);
1134        refs.add(fac.newReference
1135            ("#xpointer(id('to-be-signed'))",
1136             fac.newDigestMethod(DigestMethod.SHA1, null),
1137             Collections.singletonList
1138                (fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)),
1139             null, null));
1140
1141        // create reference 3
1142        refs.add(fac.newReference
1143            ("#xpointer(id('to-be-signed'))",
1144             fac.newDigestMethod(DigestMethod.SHA1, null),
1145             Collections.singletonList(fac.newTransform
1146                (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
1147                 (TransformParameterSpec) null)),
1148             null, null));
1149
1150        // create reference 4
1151        prefixList = new ArrayList<>(2);
1152        prefixList.add("bar");
1153        prefixList.add("#default");
1154        params = new ExcC14NParameterSpec(prefixList);
1155        refs.add(fac.newReference
1156            ("#xpointer(id('to-be-signed'))",
1157             fac.newDigestMethod(DigestMethod.SHA1, null),
1158             Collections.singletonList(fac.newTransform
1159                (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)),
1160             null, null));
1161
1162        // create SignedInfo
1163        SignedInfo si = fac.newSignedInfo(
1164            fac.newCanonicalizationMethod
1165                (CanonicalizationMethod.EXCLUSIVE,
1166                 (C14NMethodParameterSpec) null),
1167            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);
1168
1169        // create KeyInfo
1170        List<XMLStructure> kits = new ArrayList<>(2);
1171        kits.add(kifac.newKeyValue(validatingKey));
1172        KeyInfo ki = kifac.newKeyInfo(kits);
1173
1174        // create Objects
1175        Document doc = db.newDocument();
1176        Element baz = doc.createElementNS("urn:bar", "bar:Baz");
1177        Comment com = doc.createComment(" comment ");
1178        baz.appendChild(com);
1179        XMLObject obj = fac.newXMLObject(Collections.singletonList
1180            (new DOMStructure(baz)), "to-be-signed", null, null);
1181
1182        // create XMLSignature
1183        XMLSignature sig = fac.newXMLSignature
1184            (si, ki, Collections.singletonList(obj), null, null);
1185
1186        Element foo = doc.createElementNS("urn:foo", "Foo");
1187        foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");
1188        foo.setAttributeNS
1189            ("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");
1190        doc.appendChild(foo);
1191
1192        DOMSignContext dsc = new DOMSignContext(signingKey, foo);
1193        dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");
1194
1195        sig.sign(dsc);
1196
1197//      dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1198
1199        DOMValidateContext dvc = new DOMValidateContext
1200            (new KeySelectors.KeyValueKeySelector(), foo.getLastChild());
1201        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1202
1203        if (sig.equals(sig2) == false) {
1204            throw new Exception
1205                ("Unmarshalled signature is not equal to generated signature");
1206        }
1207        if (sig2.validate(dvc) == false) {
1208            throw new Exception("Validation of generated signature failed");
1209        }
1210        System.out.println();
1211    }
1212
1213    static void test_create_sign_spec() throws Exception {
1214        System.out.println("* Generating sign-spec.xml");
1215        List<Reference> refs = new ArrayList<>(2);
1216
1217        // create reference 1
1218        List<XPathType> types = new ArrayList<>(3);
1219        types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT));
1220        types.add(new XPathType(" //NotToBeSigned ",
1221            XPathType.Filter.SUBTRACT));
1222        types.add(new XPathType(" //ReallyToBeSigned ",
1223            XPathType.Filter.UNION));
1224        XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);
1225        refs.add(fac.newReference
1226            ("", fac.newDigestMethod(DigestMethod.SHA1, null),
1227             Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)),
1228             null, null));
1229
1230        // create reference 2
1231        List<Transform> trans2 = new ArrayList<>(2);
1232        trans2.add(fac.newTransform(Transform.ENVELOPED,
1233            (TransformParameterSpec) null));
1234        XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec
1235            (Collections.singletonList
1236                (new XPathType(" / ", XPathType.Filter.UNION)));
1237        trans2.add(fac.newTransform(Transform.XPATH2, xp2));
1238        refs.add(fac.newReference("#signature-value",
1239            fac.newDigestMethod(DigestMethod.SHA1, null), trans2, null, null));
1240
1241        // create SignedInfo
1242        SignedInfo si = fac.newSignedInfo(
1243            fac.newCanonicalizationMethod
1244                (CanonicalizationMethod.INCLUSIVE,
1245                 (C14NMethodParameterSpec) null),
1246            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);
1247
1248        // create KeyInfo
1249        List<XMLStructure> kits = new ArrayList<>(2);
1250        kits.add(kifac.newKeyValue(validatingKey));
1251        List<Object> xds = new ArrayList<>(2);
1252        xds.add("CN=User");
1253        xds.add(signingCert);
1254        kits.add(kifac.newX509Data(xds));
1255        KeyInfo ki = kifac.newKeyInfo(kits);
1256
1257        // create XMLSignature
1258        XMLSignature sig = fac.newXMLSignature
1259            (si, ki, null, null, "signature-value");
1260
1261        Document doc = db.newDocument();
1262        Element tbs1 = doc.createElementNS(null, "ToBeSigned");
1263        Comment tbs1Com = doc.createComment(" comment ");
1264        Element tbs1Data = doc.createElementNS(null, "Data");
1265        Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned");
1266        Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned");
1267        Comment tbs1rtbsCom = doc.createComment(" comment ");
1268        Element tbs1rtbsData = doc.createElementNS(null, "Data");
1269        tbs1rtbs.appendChild(tbs1rtbsCom);
1270        tbs1rtbs.appendChild(tbs1rtbsData);
1271        tbs1ntbs.appendChild(tbs1rtbs);
1272        tbs1.appendChild(tbs1Com);
1273        tbs1.appendChild(tbs1Data);
1274        tbs1.appendChild(tbs1ntbs);
1275
1276        Element tbs2 = doc.createElementNS(null, "ToBeSigned");
1277        Element tbs2Data = doc.createElementNS(null, "Data");
1278        Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned");
1279        Element tbs2ntbsData = doc.createElementNS(null, "Data");
1280        tbs2ntbs.appendChild(tbs2ntbsData);
1281        tbs2.appendChild(tbs2Data);
1282        tbs2.appendChild(tbs2ntbs);
1283
1284        Element document = doc.createElementNS(null, "Document");
1285        document.appendChild(tbs1);
1286        document.appendChild(tbs2);
1287        doc.appendChild(document);
1288
1289        DOMSignContext dsc = new DOMSignContext(signingKey, document);
1290
1291        sig.sign(dsc);
1292
1293//      dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1294
1295        DOMValidateContext dvc = new DOMValidateContext
1296            (new KeySelectors.KeyValueKeySelector(), document.getLastChild());
1297        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1298
1299        if (sig.equals(sig2) == false) {
1300            throw new Exception
1301                ("Unmarshalled signature is not equal to generated signature");
1302        }
1303        if (sig2.validate(dvc) == false) {
1304            throw new Exception("Validation of generated signature failed");
1305        }
1306        System.out.println();
1307    }
1308
1309    static void test_create_detached_signature(String canonicalizationMethod,
1310            String signatureMethod, String transform, KeyInfoType keyInfo,
1311            Content contentType, int port, boolean expectedFailure,
1312            Class expectedException) {
1313
1314        final String digestMethod = DigestMethod.SHA1;
1315        System.out.println("Test detached signature:");
1316        System.out.println("    Canonicalization method: "
1317                + canonicalizationMethod);
1318        System.out.println("    Signature method: " + signatureMethod);
1319        System.out.println("    Transform: " + transform);
1320        System.out.println("    Digest method: " + digestMethod);
1321        System.out.println("    KeyInfoType: " + keyInfo);
1322        System.out.println("    Content type: " + contentType);
1323        System.out.println("    Expected failure: "
1324                + (expectedFailure ? "yes" : "no"));
1325        System.out.println("    Expected exception: "
1326                + (expectedException == null ?
1327                        "no" : expectedException.getName()));
1328
1329        try {
1330            boolean success = test_create_detached_signature(
1331                    canonicalizationMethod,
1332                    signatureMethod,
1333                    digestMethod,
1334                    transform,
1335                    keyInfo,
1336                    contentType,
1337                    port);
1338
1339            if (success && expectedFailure) {
1340                System.out.println("Signature validation unexpectedly passed");
1341                result = false;
1342            } else if (!success && !expectedFailure) {
1343                System.out.println("Signature validation unexpectedly failed");
1344                result = false;
1345            } else if (expectedException != null) {
1346                System.out.println("Expected " + expectedException
1347                        + " not thrown");
1348                result = false;
1349            }
1350        } catch (Exception e) {
1351            if (expectedException == null
1352                    || !e.getClass().isAssignableFrom(expectedException)) {
1353                System.out.println("Unexpected exception: " + e);
1354                e.printStackTrace(System.out);
1355                result = false;
1356            } else {
1357                System.out.println("Expected exception: " + e);
1358            }
1359        }
1360
1361        System.out.println("Test case passed");
1362    }
1363
1364    static boolean test_create_detached_signature(String canonicalizationMethod,
1365            String signatureMethod, String digestMethod, String transform,
1366            KeyInfoType keyInfo, Content contentType, int port)
1367            throws Exception {
1368
1369        System.out.print("Sign ...");
1370
1371        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1372        dbf.setNamespaceAware(true);
1373        dbf.setValidating(false);
1374
1375        // Create SignedInfo
1376        DigestMethod dm = fac.newDigestMethod(digestMethod, null);
1377
1378        List transformList = null;
1379        if (transform != null) {
1380            TransformParameterSpec params = null;
1381            switch (transform) {
1382                case Transform.XPATH:
1383                    params = new XPathFilterParameterSpec("//.");
1384                    break;
1385                case Transform.XPATH2:
1386                    params = new XPathFilter2ParameterSpec(
1387                            Collections.singletonList(new XPathType("//.",
1388                                    XPathType.Filter.INTERSECT)));
1389                    break;
1390                case Transform.XSLT:
1391                    Element element = dbf.newDocumentBuilder()
1392                            .parse(new ByteArrayInputStream(xslt.getBytes()))
1393                            .getDocumentElement();
1394                    DOMStructure stylesheet = new DOMStructure(element);
1395                    params = new XSLTTransformParameterSpec(stylesheet);
1396                    break;
1397            }
1398            transformList = Collections.singletonList(fac.newTransform(
1399                    transform, params));
1400        }
1401
1402        String url = String.format("http://localhost:%d/%s", port, contentType);
1403        List refs = Collections.singletonList(fac.newReference(url, dm,
1404                transformList, null, null));
1405
1406        CanonicalizationMethod cm = fac.newCanonicalizationMethod(
1407                canonicalizationMethod, (C14NMethodParameterSpec) null);
1408
1409        SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
1410
1411        Key signingKey;
1412        Key validationKey;
1413        switch (signatureMethod) {
1414            case SignatureMethod.DSA_SHA1:
1415            case SignatureMethod.RSA_SHA1:
1416                KeyPair kp = generateKeyPair(sm);
1417                validationKey = kp.getPublic();
1418                signingKey = kp.getPrivate();
1419                break;
1420            case SignatureMethod.HMAC_SHA1:
1421                KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
1422                signingKey = kg.generateKey();
1423                validationKey = signingKey;
1424                break;
1425            default:
1426                throw new RuntimeException("Unsupported signature algorithm");
1427        }
1428
1429        SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
1430
1431        // Create KeyInfo
1432        KeyInfoFactory kif = fac.getKeyInfoFactory();
1433        List list = null;
1434        if (keyInfo == KeyInfoType.KeyValue) {
1435            if (validationKey instanceof PublicKey) {
1436                KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
1437                list = Collections.singletonList(kv);
1438            }
1439        } else if (keyInfo == KeyInfoType.x509data) {
1440            list = Collections.singletonList(
1441                    kif.newX509Data(Collections.singletonList("cn=Test")));
1442        } else if (keyInfo == KeyInfoType.KeyName) {
1443            list = Collections.singletonList(kif.newKeyName("Test"));
1444        } else {
1445            throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
1446        }
1447        KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
1448
1449        // Create an empty doc for detached signature
1450        Document doc = dbf.newDocumentBuilder().newDocument();
1451        DOMSignContext xsc = new DOMSignContext(signingKey, doc);
1452
1453        // Generate signature
1454        XMLSignature signature = fac.newXMLSignature(si, ki);
1455        signature.sign(xsc);
1456
1457        // Save signature
1458        String signatureString;
1459        try (StringWriter writer = new StringWriter()) {
1460            TransformerFactory tf = TransformerFactory.newInstance();
1461            Transformer trans = tf.newTransformer();
1462            Node parent = xsc.getParent();
1463            trans.transform(new DOMSource(parent), new StreamResult(writer));
1464            signatureString = writer.toString();
1465        }
1466
1467        System.out.print("Validate ... ");
1468        try (ByteArrayInputStream bis = new ByteArrayInputStream(
1469                signatureString.getBytes())) {
1470            doc = dbf.newDocumentBuilder().parse(bis);
1471        }
1472
1473        NodeList nodeLst = doc.getElementsByTagName("Signature");
1474        Node node = nodeLst.item(0);
1475        if (node == null) {
1476            throw new RuntimeException("Couldn't find Signature element");
1477        }
1478        if (!(node instanceof Element)) {
1479            throw new RuntimeException("Unexpected node type");
1480        }
1481        Element sig = (Element) node;
1482
1483        // Validate signature
1484        DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
1485        vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
1486        signature = fac.unmarshalXMLSignature(vc);
1487
1488        boolean success = signature.validate(vc);
1489        if (!success) {
1490            System.out.println("Core signature validation failed");
1491            return false;
1492        }
1493
1494        success = signature.getSignatureValue().validate(vc);
1495        if (!success) {
1496            System.out.println("Cryptographic validation of signature failed");
1497            return false;
1498        }
1499
1500        return true;
1501    }
1502
1503    private static final String DSA_Y =
1504        "070662842167565771936588335128634396171789331656318483584455493822" +
1505        "400811200853331373030669235424928346190274044631949560438023934623" +
1506        "71310375123430985057160";
1507    private static final String DSA_P =
1508        "013232376895198612407547930718267435757728527029623408872245156039" +
1509        "757713029036368719146452186041204237350521785240337048752071462798" +
1510        "273003935646236777459223";
1511    private static final String DSA_Q =
1512        "0857393771208094202104259627990318636601332086981";
1513    private static final String DSA_G =
1514        "054216440574364751416096484883257051280474283943804743768346673007" +
1515        "661082626139005426812890807137245973106730741193551360857959820973" +
1516        "90670890367185141189796";
1517    private static final String DSA_X =
1518        "0527140396812450214498055937934275626078768840117";
1519    private static final String DSA_2048_Y =
1520        "15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928";
1521    private static final String DSA_2048_P =
1522        "18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359";
1523    private static final String DSA_2048_Q =
1524        "19689526866605154788513693571065914024068069442724893395618704484701";
1525    private static final String DSA_2048_G =
1526        "2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430";
1527    private static final String DSA_2048_X =
1528        "14562787764977288900757387442281559936279834964901963465277698843172";
1529    private static final String RSA_MOD =
1530        "010800185049102889923150759252557522305032794699952150943573164381" +
1531        "936603255999071981574575044810461362008102247767482738822150129277" +
1532        "490998033971789476107463";
1533    private static final String RSA_PRIV =
1534        "016116973584421969795445996229612671947635798429212816611707210835" +
1535        "915586591340598683996088487065438751488342251960069575392056288063" +
1536        "6800379454345804879553";
1537    private static final String RSA_PUB = "065537";
1538    private static final String RSA_1024_MOD = "098871307553789439961130765" +
1539        "909423744508062468450669519128736624058048856940468016843888594585" +
1540        "322862378444314635412341974900625010364163960238734457710620107530" +
1541        "573945081856371709138380902553309075505688814637544923038853658690" +
1542        "857672483016239697038853418682988686871489963827000080098971762923" +
1543        "833614557257607521";
1544    private static final String RSA_1024_PRIV = "03682574144968491431483287" +
1545        "297021581096848810374110568017963075809477047466189822987258068867" +
1546        "704855380407747867998863645890602646601140183818953428006646987710" +
1547        "237008997971129772408397621801631622129297063463868593083106979716" +
1548        "204903524890556839550490384015324575598723478554854070823335021842" +
1549        "210112348400928769";
1550    private static final String EC_P256_X =
1551        "335863644451761614592446380116804721648611739647823420286081723541" +
1552        "6166183710";
1553    private static final String EC_P256_Y =
1554        "951559601159729477487064127150143688502130342917782252098602422796" +
1555        "95457910701";
1556    private static final String EC_P256_S =
1557        "425976209773168452211813225517384419928639977904006759709292218082" +
1558        "7440083936";
1559    private static final ECParameterSpec EC_P256_PARAMS = initECParams(
1560        "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",
1561        "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",
1562        "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B",
1563        "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
1564        "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",
1565        "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551",
1566        1
1567    );
1568    private static final String EC_P384_X =
1569        "12144058647679082341340699736608428955270957565259459672517275506071643671835484144490620216582303669654008841724053";
1570    private static final String EC_P384_Y =
1571        "18287745972107701566600963632634101287058332546756092926848497481238534346489545826483592906634896557151987868614320";
1572    private static final String EC_P384_S =
1573        "10307785759830534742680442271492590599236624208247590184679565032330507874096079979152605984203102224450595283943382";
1574    private static final ECParameterSpec EC_P384_PARAMS = initECParams(
1575        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF",
1576        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC",
1577        "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF",
1578        "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7",
1579        "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F",
1580        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973",
1581        1
1582    );
1583    private static final String EC_P521_X =
1584        "4157918188927862838251799402582135611021257663417126086145819679867926857146776190737187582274664373117054717389603317411991660346043842712448912355335343997";
1585    private static final String EC_P521_Y =
1586        "4102838062751704796157456866854813794620023146924181568434486703918224542844053923233919899911519054998554969832861957437850996213216829205401947264294066288";
1587    private static final String EC_P521_S =
1588        "4857798533181496041050215963883119936300918353498701880968530610687256097257307590162398707429640390843595868713096292822034014722985178583665959048714417342";
1589    private static final ECParameterSpec EC_P521_PARAMS = initECParams(
1590        "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
1591        "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC",
1592        "0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00",
1593        "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66",
1594        "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650",
1595        "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409",
1596        1
1597    );
1598
1599    private static ECParameterSpec initECParams(
1600            String sfield, String a, String b, String gx, String gy,
1601            String n, int h) {
1602        ECField field = new ECFieldFp(bigInt(sfield));
1603        EllipticCurve curve = new EllipticCurve(field,
1604                                                bigInt(a), bigInt(b));
1605        ECPoint g = new ECPoint(bigInt(gx), bigInt(gy));
1606        return new ECParameterSpec(curve, g, bigInt(n), h);
1607    }
1608
1609    private static BigInteger bigInt(String s) {
1610        return new BigInteger(s, 16);
1611    }
1612    private static PublicKey getPublicKey(String algo, int keysize)
1613        throws Exception {
1614        KeyFactory kf = KeyFactory.getInstance(algo);
1615        KeySpec kspec;
1616        if (algo.equalsIgnoreCase("DSA")) {
1617            if (keysize == 1024) {
1618                kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),
1619                                             new BigInteger(DSA_P),
1620                                             new BigInteger(DSA_Q),
1621                                             new BigInteger(DSA_G));
1622            } else if (keysize == 2048) {
1623                kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y),
1624                                             new BigInteger(DSA_2048_P),
1625                                             new BigInteger(DSA_2048_Q),
1626                                             new BigInteger(DSA_2048_G));
1627            } else throw new RuntimeException("Unsupported keysize:" + keysize);
1628        } else if (algo.equalsIgnoreCase("RSA")) {
1629            if (keysize == 512) {
1630                kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD),
1631                                             new BigInteger(RSA_PUB));
1632            } else if (keysize == 1024) {
1633                kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),
1634                                             new BigInteger(RSA_PUB));
1635            } else throw new RuntimeException("Unsupported keysize:" + keysize);
1636        } else throw new RuntimeException("Unsupported key algorithm " + algo);
1637        return kf.generatePublic(kspec);
1638    }
1639
1640    private static PublicKey getECPublicKey(String curve) throws Exception {
1641        KeyFactory kf = KeyFactory.getInstance("EC");
1642        String x, y;
1643        ECParameterSpec params;
1644        switch (curve) {
1645            case "P256":
1646                x = EC_P256_X;
1647                y = EC_P256_Y;
1648                params = EC_P256_PARAMS;
1649                break;
1650            case "P384":
1651                x = EC_P384_X;
1652                y = EC_P384_Y;
1653                params = EC_P384_PARAMS;
1654                break;
1655            case "P521":
1656                x = EC_P521_X;
1657                y = EC_P521_Y;
1658                params = EC_P521_PARAMS;
1659                break;
1660            default:
1661                throw new Exception("Unsupported curve: " + curve);
1662        }
1663        KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x),
1664                                                        new BigInteger(y)),
1665                                            params);
1666        return kf.generatePublic(kspec);
1667    }
1668
1669    private static PrivateKey getPrivateKey(String algo, int keysize)
1670        throws Exception {
1671        KeyFactory kf = KeyFactory.getInstance(algo);
1672        KeySpec kspec;
1673        if (algo.equalsIgnoreCase("DSA")) {
1674            if (keysize == 1024) {
1675                kspec = new DSAPrivateKeySpec
1676                    (new BigInteger(DSA_X), new BigInteger(DSA_P),
1677                     new BigInteger(DSA_Q), new BigInteger(DSA_G));
1678            } else if (keysize == 2048) {
1679                kspec = new DSAPrivateKeySpec
1680                    (new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P),
1681                     new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));
1682            } else throw new RuntimeException("Unsupported keysize:" + keysize);
1683        } else if (algo.equalsIgnoreCase("RSA")) {
1684            if (keysize == 512) {
1685                kspec = new RSAPrivateKeySpec
1686                    (new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV));
1687            } else {
1688                kspec = new RSAPrivateKeySpec(new BigInteger(RSA_1024_MOD),
1689                                              new BigInteger(RSA_1024_PRIV));
1690            }
1691        } else throw new RuntimeException("Unsupported key algorithm " + algo);
1692        return kf.generatePrivate(kspec);
1693    }
1694
1695    private static PrivateKey getECPrivateKey(String curve) throws Exception {
1696        String s;
1697        ECParameterSpec params;
1698        switch (curve) {
1699            case "P256":
1700                s = EC_P256_S;
1701                params = EC_P256_PARAMS;
1702                break;
1703            case "P384":
1704                s = EC_P384_S;
1705                params = EC_P384_PARAMS;
1706                break;
1707            case "P521":
1708                s = EC_P521_S;
1709                params = EC_P521_PARAMS;
1710                break;
1711            default:
1712                throw new Exception("Unsupported curve: " + curve);
1713        }
1714        KeyFactory kf = KeyFactory.getInstance("EC");
1715        KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);
1716        return kf.generatePrivate(kspec);
1717    }
1718
1719    private static SecretKey getSecretKey(final byte[] secret) {
1720        return new SecretKey() {
1721            public String getFormat()   { return "RAW"; }
1722            public byte[] getEncoded()  { return secret; }
1723            public String getAlgorithm(){ return "SECRET"; }
1724        };
1725    }
1726
1727    static KeyPair generateKeyPair(SignatureMethod sm)
1728            throws NoSuchAlgorithmException {
1729        KeyPairGenerator keygen;
1730        switch (sm.getAlgorithm()) {
1731            case SignatureMethod.DSA_SHA1:
1732                keygen = KeyPairGenerator.getInstance("DSA");
1733                break;
1734            case SignatureMethod.RSA_SHA1:
1735                keygen = KeyPairGenerator.getInstance("RSA");
1736                break;
1737            default:
1738                throw new RuntimeException("Unsupported signature algorithm");
1739        }
1740
1741        SecureRandom random = new SecureRandom();
1742        keygen.initialize(1024, random);
1743        return keygen.generateKeyPair();
1744    }
1745
1746    /**
1747     * This URIDereferencer returns locally cached copies of http content to
1748     * avoid test failures due to network glitches, etc.
1749     */
1750    private static class HttpURIDereferencer implements URIDereferencer {
1751        private URIDereferencer defaultUd;
1752
1753        HttpURIDereferencer() {
1754            defaultUd = XMLSignatureFactory.getInstance().getURIDereferencer();
1755        }
1756
1757        public Data dereference(final URIReference ref, XMLCryptoContext ctx)
1758        throws URIReferenceException {
1759            String uri = ref.getURI();
1760            if (uri.equals(STYLESHEET) || uri.equals(STYLESHEET_B64)) {
1761                try {
1762                    FileInputStream fis = new FileInputStream(new File
1763                        (DATA_DIR, uri.substring(uri.lastIndexOf('/'))));
1764                    return new OctetStreamData(fis,ref.getURI(),ref.getType());
1765                } catch (Exception e) { throw new URIReferenceException(e); }
1766            }
1767
1768            // fallback on builtin deref
1769            return defaultUd.dereference(ref, ctx);
1770        }
1771    }
1772
1773    // local http server
1774    static class Http implements HttpHandler, AutoCloseable {
1775
1776        private final HttpServer server;
1777
1778        private Http(HttpServer server) {
1779            this.server = server;
1780        }
1781
1782        static Http startServer() throws IOException {
1783            HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
1784            return new Http(server);
1785        }
1786
1787        void start() {
1788            server.createContext("/", this);
1789            server.start();
1790        }
1791
1792        void stop() {
1793            server.stop(0);
1794        }
1795
1796        int getPort() {
1797            return server.getAddress().getPort();
1798        }
1799
1800        @Override
1801        public void handle(HttpExchange t) throws IOException {
1802            try {
1803                String type;
1804                String path = t.getRequestURI().getPath();
1805                if (path.startsWith("/")) {
1806                    type = path.substring(1);
1807                } else {
1808                    type = path;
1809                }
1810
1811                String contentTypeHeader = "";
1812                byte[] output = new byte[] {};
1813                int code = 200;
1814                Content testContentType = Content.valueOf(type);
1815                switch (testContentType) {
1816                    case Base64:
1817                        contentTypeHeader = "application/octet-stream";
1818                        output = "VGVzdA==".getBytes();
1819                        break;
1820                    case Text:
1821                        contentTypeHeader = "text/plain";
1822                        output = "Text".getBytes();
1823                        break;
1824                    case Xml:
1825                        contentTypeHeader = "application/xml";
1826                        output = "<tag>test</tag>".getBytes();
1827                        break;
1828                    case NotExisitng:
1829                        code = 404;
1830                        break;
1831                    default:
1832                        throw new IOException("Unknown test content type");
1833                }
1834
1835                t.getResponseHeaders().set("Content-Type", contentTypeHeader);
1836                t.sendResponseHeaders(code, output.length);
1837                t.getResponseBody().write(output);
1838            } catch (IOException e) {
1839                System.out.println("Exception: " + e);
1840                t.sendResponseHeaders(500, 0);
1841            }
1842            t.close();
1843        }
1844
1845        @Override
1846        public void close() {
1847            stop();
1848        }
1849    }
1850}
1851