Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/test/jdk/javax/xml/crypto/dsig/GenerationTests.java
66646 views
1
/*
2
* Copyright (c) 2005, 2021, 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 8177334 8205507 8210736 8217878 8241306
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
* @library /test/lib
34
* @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
35
* X509KeySelector.java GenerationTests.java
36
* @run main/othervm/timeout=300 -Dsun.net.httpserver.nodelay=true GenerationTests
37
* @author Sean Mullan
38
*/
39
40
import com.sun.net.httpserver.HttpExchange;
41
import com.sun.net.httpserver.HttpHandler;
42
import com.sun.net.httpserver.HttpServer;
43
import java.io.*;
44
import java.lang.reflect.Modifier;
45
import java.math.BigInteger;
46
import java.net.InetSocketAddress;
47
import java.security.Key;
48
import java.security.KeyFactory;
49
import java.security.KeyPair;
50
import java.security.KeyPairGenerator;
51
import java.security.KeyStore;
52
import java.security.NoSuchAlgorithmException;
53
import java.security.PrivateKey;
54
import java.security.PublicKey;
55
import java.security.cert.Certificate;
56
import java.security.cert.CertificateFactory;
57
import java.security.cert.X509CRL;
58
import java.security.spec.KeySpec;
59
import java.security.spec.DSAPrivateKeySpec;
60
import java.security.spec.DSAPublicKeySpec;
61
import java.security.spec.ECField;
62
import java.security.spec.ECFieldFp;
63
import java.security.spec.ECParameterSpec;
64
import java.security.spec.ECPoint;
65
import java.security.spec.ECPrivateKeySpec;
66
import java.security.spec.ECPublicKeySpec;
67
import java.security.spec.EllipticCurve;
68
import java.security.spec.RSAPrivateKeySpec;
69
import java.security.spec.RSAPublicKeySpec;
70
import java.util.*;
71
import java.util.stream.Stream;
72
import javax.crypto.KeyGenerator;
73
import javax.crypto.SecretKey;
74
import javax.xml.XMLConstants;
75
import javax.xml.parsers.*;
76
import javax.xml.crypto.Data;
77
import javax.xml.crypto.KeySelector;
78
import javax.xml.crypto.OctetStreamData;
79
import javax.xml.crypto.URIDereferencer;
80
import javax.xml.crypto.URIReference;
81
import javax.xml.crypto.URIReferenceException;
82
import javax.xml.crypto.XMLCryptoContext;
83
import javax.xml.crypto.XMLStructure;
84
import javax.xml.crypto.dsig.*;
85
import javax.xml.crypto.dom.*;
86
import javax.xml.crypto.dsig.dom.DOMSignContext;
87
import javax.xml.crypto.dsig.dom.DOMValidateContext;
88
import javax.xml.crypto.dsig.keyinfo.*;
89
import javax.xml.crypto.dsig.spec.*;
90
import javax.xml.transform.*;
91
import javax.xml.transform.dom.DOMSource;
92
import javax.xml.transform.stream.StreamResult;
93
import org.w3c.dom.*;
94
95
import jdk.test.lib.security.SecurityUtils;
96
97
/**
98
* Test that recreates merlin-xmldsig-twenty-three test vectors (and more)
99
* but with different keys and X.509 data.
100
*/
101
public class GenerationTests {
102
103
private static XMLSignatureFactory fac;
104
private static KeyInfoFactory kifac;
105
private static DocumentBuilder db;
106
private static CanonicalizationMethod withoutComments;
107
private static SignatureMethod dsaSha1, dsaSha256,
108
rsaSha1, rsaSha224, rsaSha256, rsaSha384, rsaSha512,
109
ecdsaSha1, ecdsaSha224, ecdsaSha256, ecdsaSha384, ecdsaSha512,
110
hmacSha1, hmacSha224, hmacSha256, hmacSha384, hmacSha512,
111
rsaSha1mgf1, rsaSha224mgf1, rsaSha256mgf1, rsaSha384mgf1, rsaSha512mgf1, rsaShaPSS;
112
private static DigestMethod sha1, sha224, sha256, sha384, sha512,
113
sha3_224, sha3_256, sha3_384, sha3_512;
114
private static KeyInfo dsa1024, dsa2048, rsa, rsa1024, rsa2048,
115
p256ki, p384ki, p521ki;
116
private static KeySelector kvks = new KeySelectors.KeyValueKeySelector();
117
private static KeySelector sks;
118
private static Key signingKey;
119
private static PublicKey validatingKey;
120
private static Certificate signingCert;
121
private static KeyStore ks;
122
private final static String DIR = System.getProperty("test.src", ".");
123
// private final static String DIR = ".";
124
private final static String DATA_DIR =
125
DIR + System.getProperty("file.separator") + "data";
126
private final static String KEYSTORE =
127
DATA_DIR + System.getProperty("file.separator") + "certs" +
128
System.getProperty("file.separator") + "test.jks";
129
private final static String CRL =
130
DATA_DIR + System.getProperty("file.separator") + "certs" +
131
System.getProperty("file.separator") + "crl";
132
// XML Document with a DOCTYPE declaration
133
private final static String ENVELOPE =
134
DATA_DIR + System.getProperty("file.separator") + "envelope.xml";
135
// XML Document without a DOCTYPE declaration
136
private final static String ENVELOPE2 =
137
DATA_DIR + System.getProperty("file.separator") + "envelope2.xml";
138
private static URIDereferencer httpUd = null;
139
private final static String STYLESHEET =
140
"http://www.w3.org/TR/xml-stylesheet";
141
private final static String STYLESHEET_B64 =
142
"http://www.w3.org/Signature/2002/04/xml-stylesheet.b64";
143
private final static String DSA_SHA256 =
144
"http://www.w3.org/2009/xmldsig11#dsa-sha256";
145
146
private static final String BOGUS = "bogus";
147
148
private static final String xslt = ""
149
+ "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'\n"
150
+ " xmlns='http://www.w3.org/TR/xhtml1/strict' \n"
151
+ " exclude-result-prefixes='foo' \n"
152
+ " version='1.0'>\n"
153
+ " <xsl:output encoding='UTF-8' \n"
154
+ " indent='no' \n"
155
+ " method='xml' />\n"
156
+ " <xsl:template match='/'>\n"
157
+ " <html>\n"
158
+ " <head>\n"
159
+ " <title>Notaries</title>\n"
160
+ " </head>\n"
161
+ " <body>\n"
162
+ " <table>\n"
163
+ " <xsl:for-each select='Notaries/Notary'>\n"
164
+ " <tr>\n"
165
+ " <th>\n"
166
+ " <xsl:value-of select='@name' />\n"
167
+ " </th>\n"
168
+ " </tr>\n"
169
+ " </xsl:for-each>\n"
170
+ " </table>\n"
171
+ " </body>\n"
172
+ " </html>\n"
173
+ " </xsl:template>\n"
174
+ "</xsl:stylesheet>\n";
175
176
private static final String[] canonicalizationMethods = new String[] {
177
CanonicalizationMethod.EXCLUSIVE,
178
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
179
CanonicalizationMethod.INCLUSIVE,
180
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS
181
};
182
183
private static final String[] xml_transforms = new String[] {
184
Transform.XSLT,
185
Transform.XPATH,
186
Transform.XPATH2,
187
CanonicalizationMethod.EXCLUSIVE,
188
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
189
CanonicalizationMethod.INCLUSIVE,
190
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
191
};
192
193
private static final String[] non_xml_transforms = new String[] {
194
null, Transform.BASE64
195
};
196
197
// It will be too time consuming to test all combinations of
198
// all digest methods and signature methods. So we pick some
199
// majors one and only test a combination when a major method
200
// (either digest or signature) is included.
201
//
202
// * * *
203
// * * *
204
// * * *
205
// * * * * * * * * *
206
// * * * * * * * * *
207
// * * * * * * * * *
208
// * * *
209
// * * *
210
// * * *
211
212
private static List<String> majorSignatureMethods = List.of(
213
SignatureMethod.DSA_SHA256,
214
SignatureMethod.RSA_SHA256,
215
SignatureMethod.ECDSA_SHA256,
216
SignatureMethod.HMAC_SHA256,
217
SignatureMethod.SHA256_RSA_MGF1,
218
SignatureMethod.RSA_PSS);
219
220
private static final String[] allSignatureMethods
221
= Stream.of(SignatureMethod.class.getDeclaredFields())
222
.filter(f -> Modifier.isStatic(f.getModifiers()))
223
.map(f -> {
224
try {
225
return (String)f.get(null);
226
} catch (Exception e) {
227
throw new Error("should not happen");
228
}
229
})
230
.toArray(String[]::new);
231
232
private static final List<String> majorDigestMethods = List.of(
233
DigestMethod.SHA1,
234
DigestMethod.SHA256,
235
DigestMethod.SHA3_256);
236
237
private static final String[] allDigestMethods
238
= Stream.of(DigestMethod.class.getDeclaredFields())
239
.filter(f -> Modifier.isStatic(f.getModifiers())
240
&& !f.getName().equals("RIPEMD160"))
241
.map(f -> {
242
try {
243
return (String)f.get(null);
244
} catch (Exception e) {
245
throw new Error("should not happen");
246
}
247
})
248
.toArray(String[]::new);
249
250
// As of JDK 17, the number of defined algorithms are...
251
static {
252
if (allSignatureMethods.length != 23
253
|| allDigestMethods.length != 9) {
254
System.out.println(Arrays.toString(allSignatureMethods));
255
System.out.println(Arrays.toString(allDigestMethods));
256
throw new AssertionError("Not all methods are counted");
257
}
258
}
259
260
private static enum Content {
261
Xml, Text, Base64, NotExisitng
262
}
263
264
private static enum KeyInfoType {
265
KeyValue, x509data, KeyName
266
}
267
268
// cached keys (for performance) used by test_create_detached_signature().
269
private static HashMap<String,Key[]> cachedKeys = new HashMap<>();
270
271
// Load cachedKeys persisted in a file to reproduce a failure.
272
// The keys are always saved to "cached-keys" but you can rename
273
// it to a different file name and load it here. Note: The keys will
274
// always be persisted so renaming is a good idea although the
275
// content might not change.
276
static {
277
String cacheFile = System.getProperty("use.cached.keys");
278
if (cacheFile != null) {
279
try (FileInputStream fis = new FileInputStream(cacheFile);
280
ObjectInputStream ois = new ObjectInputStream(fis)) {
281
cachedKeys = (HashMap<String,Key[]>) ois.readObject();
282
} catch (Exception e) {
283
throw new AssertionError("Cannot read " + cacheFile, e);
284
}
285
}
286
}
287
288
private static boolean result = true;
289
290
public static void main(String args[]) throws Exception {
291
// Re-enable sha1 algs
292
SecurityUtils.removeAlgsFromDSigPolicy("sha1");
293
294
setup();
295
test_create_signature_enveloped_dsa(1024);
296
test_create_signature_enveloped_dsa(2048);
297
test_create_signature_enveloping_b64_dsa();
298
test_create_signature_enveloping_dsa();
299
test_create_signature_enveloping_hmac_sha1_40();
300
test_create_signature_enveloping_hmac_sha256();
301
test_create_signature_enveloping_hmac_sha224();
302
test_create_signature_enveloping_hmac_sha384();
303
test_create_signature_enveloping_hmac_sha512();
304
test_create_signature_enveloping_rsa();
305
test_create_signature_enveloping_p256_sha1();
306
test_create_signature_enveloping_p256_sha224();
307
test_create_signature_enveloping_p256_sha256();
308
test_create_signature_enveloping_p256_sha384();
309
test_create_signature_enveloping_p256_sha512();
310
test_create_signature_enveloping_p384_sha1();
311
test_create_signature_enveloping_p521_sha1();
312
test_create_signature_external_b64_dsa();
313
test_create_signature_external_dsa();
314
test_create_signature_keyname();
315
test_create_signature_retrievalmethod_rawx509crt();
316
test_create_signature_x509_crt_crl();
317
test_create_signature_x509_crt();
318
test_create_signature_x509_is();
319
test_create_signature_x509_ski();
320
test_create_signature_x509_sn();
321
test_create_signature();
322
test_create_exc_signature();
323
test_create_sign_spec();
324
test_create_signature_enveloping_sha256_dsa();
325
test_create_signature_enveloping_sha384_rsa_sha256();
326
test_create_signature_enveloping_sha224_rsa_sha256();
327
test_create_signature_enveloping_sha3_224_rsa_sha256();
328
test_create_signature_enveloping_sha3_256_rsa_sha256();
329
test_create_signature_enveloping_sha3_384_rsa_sha256();
330
test_create_signature_enveloping_sha3_512_rsa_sha256();
331
test_create_signature_enveloping_sha512_rsa_sha384();
332
test_create_signature_enveloping_sha512_rsa_sha224();
333
test_create_signature_enveloping_sha512_rsa_sha512();
334
test_create_signature_enveloping_sha512_rsa_sha1_mgf1();
335
test_create_signature_enveloping_sha512_rsa_sha224_mgf1();
336
test_create_signature_enveloping_sha512_rsa_sha256_mgf1();
337
test_create_signature_enveloping_sha512_rsa_sha384_mgf1();
338
test_create_signature_enveloping_sha512_rsa_sha512_mgf1();
339
test_create_signature_enveloping_sha512_rsa_pss();
340
test_create_signature_reference_dependency();
341
test_create_signature_with_attr_in_no_namespace();
342
test_create_signature_with_empty_id();
343
test_create_signature_enveloping_over_doc(ENVELOPE, true);
344
test_create_signature_enveloping_over_doc(ENVELOPE2, true);
345
test_create_signature_enveloping_over_doc(ENVELOPE, false);
346
test_create_signature_enveloping_dom_level1();
347
348
// run tests for detached signatures with local http server
349
try (Http server = Http.startServer()) {
350
server.start();
351
352
System.out.println("\ntests for XML documents");
353
Arrays.stream(canonicalizationMethods).forEach(c ->
354
Arrays.stream(allSignatureMethods).forEach(s ->
355
Arrays.stream(allDigestMethods).forEach(d ->
356
Arrays.stream(xml_transforms).forEach(t ->
357
Arrays.stream(KeyInfoType.values()).forEach(k -> {
358
if (isMajor(s, d)) {
359
test_create_detached_signature(c, s, d, t, k,
360
Content.Xml, server.getPort(), false, null);
361
}
362
})))));
363
364
System.out.println("\ntests for text data with no transform");
365
Arrays.stream(canonicalizationMethods).forEach(c ->
366
Arrays.stream(allSignatureMethods).forEach(s ->
367
Arrays.stream(allDigestMethods).forEach(d ->
368
Arrays.stream(KeyInfoType.values()).forEach(k -> {
369
if (isMajor(s, d)) {
370
test_create_detached_signature(c, s, d, null, k,
371
Content.Text, server.getPort(), false, null);
372
}
373
}))));
374
375
System.out.println("\ntests for base64 data");
376
Arrays.stream(canonicalizationMethods).forEach(c ->
377
Arrays.stream(allSignatureMethods).forEach(s ->
378
Arrays.stream(allDigestMethods).forEach(d ->
379
Arrays.stream(non_xml_transforms).forEach(t ->
380
Arrays.stream(KeyInfoType.values()).forEach(k -> {
381
if (isMajor(s, d)) {
382
test_create_detached_signature(c, s, d, t, k,
383
Content.Base64, server.getPort(),
384
false, null);
385
}
386
})))));
387
388
// negative tests
389
390
System.out.println("\nunknown CanonicalizationMethod");
391
test_create_detached_signature(
392
CanonicalizationMethod.EXCLUSIVE + BOGUS,
393
SignatureMethod.DSA_SHA1,
394
DigestMethod.SHA1,
395
CanonicalizationMethod.INCLUSIVE,
396
KeyInfoType.KeyName,
397
Content.Xml,
398
server.getPort(),
399
true,
400
NoSuchAlgorithmException.class);
401
402
System.out.println("\nunknown SignatureMethod");
403
test_create_detached_signature(
404
CanonicalizationMethod.EXCLUSIVE,
405
SignatureMethod.DSA_SHA1 + BOGUS,
406
DigestMethod.SHA1,
407
CanonicalizationMethod.INCLUSIVE,
408
KeyInfoType.KeyName, Content.Xml,
409
server.getPort(),
410
true,
411
NoSuchAlgorithmException.class);
412
413
System.out.println("\nunknown DigestMethod");
414
test_create_detached_signature(
415
CanonicalizationMethod.EXCLUSIVE,
416
SignatureMethod.DSA_SHA1,
417
DigestMethod.SHA1 + BOGUS,
418
CanonicalizationMethod.INCLUSIVE,
419
KeyInfoType.KeyName, Content.Xml,
420
server.getPort(),
421
true,
422
NoSuchAlgorithmException.class);
423
424
System.out.println("\nunknown Transform");
425
test_create_detached_signature(
426
CanonicalizationMethod.EXCLUSIVE,
427
SignatureMethod.DSA_SHA1,
428
DigestMethod.SHA1,
429
CanonicalizationMethod.INCLUSIVE + BOGUS,
430
KeyInfoType.KeyName, Content.Xml,
431
server.getPort(),
432
true,
433
NoSuchAlgorithmException.class);
434
435
System.out.println("\nno source document");
436
test_create_detached_signature(
437
CanonicalizationMethod.EXCLUSIVE,
438
SignatureMethod.DSA_SHA1,
439
DigestMethod.SHA1,
440
CanonicalizationMethod.INCLUSIVE,
441
KeyInfoType.KeyName,
442
Content.NotExisitng,
443
server.getPort(),
444
true,
445
XMLSignatureException.class);
446
447
System.out.println("\nwrong transform for text data");
448
test_create_detached_signature(
449
CanonicalizationMethod.EXCLUSIVE,
450
SignatureMethod.DSA_SHA1,
451
DigestMethod.SHA1,
452
CanonicalizationMethod.INCLUSIVE,
453
KeyInfoType.KeyName,
454
Content.Text,
455
server.getPort(),
456
true,
457
XMLSignatureException.class);
458
}
459
460
// persist cached keys to a file.
461
try (FileOutputStream fos = new FileOutputStream("cached-keys", true);
462
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
463
oos.writeObject(cachedKeys);
464
}
465
466
if (!result) {
467
throw new RuntimeException("At least one test case failed");
468
}
469
}
470
471
// Do not test on all combinations.
472
private static boolean isMajor(String signatureMethod, String digestMethod) {
473
return majorDigestMethods.contains(digestMethod)
474
|| majorSignatureMethods.contains(signatureMethod);
475
}
476
477
private static void setup() throws Exception {
478
fac = XMLSignatureFactory.getInstance();
479
kifac = fac.getKeyInfoFactory();
480
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
481
dbf.setNamespaceAware(true);
482
db = dbf.newDocumentBuilder();
483
484
// get key & self-signed certificate from keystore
485
FileInputStream fis = new FileInputStream(KEYSTORE);
486
ks = KeyStore.getInstance("JKS");
487
ks.load(fis, "changeit".toCharArray());
488
signingKey = ks.getKey("user", "changeit".toCharArray());
489
signingCert = ks.getCertificate("user");
490
validatingKey = signingCert.getPublicKey();
491
492
// create common objects
493
withoutComments = fac.newCanonicalizationMethod
494
(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null);
495
dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
496
dsaSha256 = fac.newSignatureMethod(DSA_SHA256, null);
497
498
sha1 = fac.newDigestMethod(DigestMethod.SHA1, null);
499
sha224 = fac.newDigestMethod(DigestMethod.SHA224, null);
500
sha256 = fac.newDigestMethod(DigestMethod.SHA256, null);
501
sha384 = fac.newDigestMethod(DigestMethod.SHA384, null);
502
sha512 = fac.newDigestMethod(DigestMethod.SHA512, null);
503
sha3_224 = fac.newDigestMethod(DigestMethod.SHA3_224, null);
504
sha3_256 = fac.newDigestMethod(DigestMethod.SHA3_256, null);
505
sha3_384 = fac.newDigestMethod(DigestMethod.SHA3_384, null);
506
sha3_512 = fac.newDigestMethod(DigestMethod.SHA3_512, null);
507
508
dsa1024 = kifac.newKeyInfo(Collections.singletonList
509
(kifac.newKeyValue(validatingKey)));
510
dsa2048 = kifac.newKeyInfo(Collections.singletonList
511
(kifac.newKeyValue(getPublicKey("DSA", 2048))));
512
rsa = kifac.newKeyInfo(Collections.singletonList
513
(kifac.newKeyValue(getPublicKey("RSA", 512))));
514
rsa1024 = kifac.newKeyInfo(Collections.singletonList
515
(kifac.newKeyValue(getPublicKey("RSA", 1024))));
516
rsa2048 = kifac.newKeyInfo(Collections.singletonList
517
(kifac.newKeyValue(getPublicKey("RSA", 2048))));
518
p256ki = kifac.newKeyInfo(Collections.singletonList
519
(kifac.newKeyValue(getECPublicKey("P256"))));
520
p384ki = kifac.newKeyInfo(Collections.singletonList
521
(kifac.newKeyValue(getECPublicKey("P384"))));
522
p521ki = kifac.newKeyInfo(Collections.singletonList
523
(kifac.newKeyValue(getECPublicKey("P521"))));
524
525
rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
526
rsaSha224 = fac.newSignatureMethod(SignatureMethod.RSA_SHA224, null);
527
rsaSha256 = fac.newSignatureMethod(SignatureMethod.RSA_SHA256, null);
528
rsaSha384 = fac.newSignatureMethod(SignatureMethod.RSA_SHA384, null);
529
rsaSha512 = fac.newSignatureMethod(SignatureMethod.RSA_SHA512, null);
530
531
rsaSha1mgf1 = fac.newSignatureMethod(SignatureMethod.SHA1_RSA_MGF1, null);
532
rsaSha224mgf1 = fac.newSignatureMethod(SignatureMethod.SHA224_RSA_MGF1, null);
533
rsaSha256mgf1 = fac.newSignatureMethod(SignatureMethod.SHA256_RSA_MGF1, null);
534
rsaSha384mgf1 = fac.newSignatureMethod(SignatureMethod.SHA384_RSA_MGF1, null);
535
rsaSha512mgf1 = fac.newSignatureMethod(SignatureMethod.SHA512_RSA_MGF1, null);
536
rsaShaPSS = fac.newSignatureMethod(SignatureMethod. RSA_PSS, null);
537
538
ecdsaSha1 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA1, null);
539
ecdsaSha224 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA224, null);
540
ecdsaSha256 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA256, null);
541
ecdsaSha384 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA384, null);
542
ecdsaSha512 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA512, null);
543
544
hmacSha1 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA1, null);
545
hmacSha224 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA224, null);
546
hmacSha256 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA256, null);
547
hmacSha384 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA384, null);
548
hmacSha512 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA512, null);
549
550
sks = new KeySelectors.SecretKeySelector("secret".getBytes("ASCII"));
551
552
httpUd = new HttpURIDereferencer();
553
}
554
555
static void test_create_signature_enveloped_dsa(int size) throws Exception {
556
System.out.println("* Generating signature-enveloped-dsa-"
557
+ size + ".xml");
558
SignatureMethod sm = null;
559
KeyInfo ki = null;
560
Key privKey;
561
if (size == 1024) {
562
sm = dsaSha1;
563
ki = dsa1024;
564
privKey = signingKey;
565
} else if (size == 2048) {
566
sm = dsaSha256;
567
ki = dsa2048;
568
privKey = getPrivateKey("DSA", 2048);
569
} else throw new RuntimeException("unsupported keysize:" + size);
570
571
// create SignedInfo
572
SignedInfo si = fac.newSignedInfo
573
(withoutComments, sm, Collections.singletonList
574
(fac.newReference
575
("", sha1, Collections.singletonList
576
(fac.newTransform(Transform.ENVELOPED,
577
(TransformParameterSpec) null)),
578
null, null)));
579
580
// create XMLSignature
581
XMLSignature sig = fac.newXMLSignature(si, ki);
582
583
Document doc = db.newDocument();
584
Element envelope = doc.createElementNS
585
("http://example.org/envelope", "Envelope");
586
envelope.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
587
"xmlns", "http://example.org/envelope");
588
doc.appendChild(envelope);
589
590
DOMSignContext dsc = new DOMSignContext(privKey, envelope);
591
592
sig.sign(dsc);
593
// StringWriter sw = new StringWriter();
594
// dumpDocument(doc, sw);
595
// System.out.println(sw.toString());
596
597
DOMValidateContext dvc = new DOMValidateContext
598
(kvks, envelope.getFirstChild());
599
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
600
601
if (sig.equals(sig2) == false) {
602
throw new Exception
603
("Unmarshalled signature is not equal to generated signature");
604
}
605
606
if (sig2.validate(dvc) == false) {
607
throw new Exception("Validation of generated signature failed");
608
}
609
System.out.println();
610
}
611
612
static void test_create_signature_enveloping_b64_dsa() throws Exception {
613
System.out.println("* Generating signature-enveloping-b64-dsa.xml");
614
test_create_signature_enveloping
615
(sha1, dsaSha1, dsa1024, signingKey, kvks, true, true);
616
System.out.println();
617
}
618
619
static void test_create_signature_enveloping_dsa() throws Exception {
620
System.out.println("* Generating signature-enveloping-dsa.xml");
621
test_create_signature_enveloping
622
(sha1, dsaSha1, dsa1024, signingKey, kvks, false, true);
623
System.out.println();
624
}
625
626
static void test_create_signature_enveloping_sha256_dsa() throws Exception {
627
System.out.println("* Generating signature-enveloping-sha256-dsa.xml");
628
test_create_signature_enveloping
629
(sha256, dsaSha1, dsa1024, signingKey, kvks, false, true);
630
System.out.println();
631
}
632
633
static void test_create_signature_enveloping_hmac_sha1_40()
634
throws Exception {
635
System.out.println("* Generating signature-enveloping-hmac-sha1-40.xml");
636
try {
637
test_create_signature_enveloping(sha1, hmacSha1, null,
638
getSecretKey("secret".getBytes("ASCII")), sks, false, true);
639
} catch (Exception e) {
640
if (!(e instanceof XMLSignatureException)) {
641
throw e;
642
}
643
}
644
System.out.println();
645
}
646
647
static void test_create_signature_enveloping_hmac_sha256()
648
throws Exception {
649
System.out.println("* Generating signature-enveloping-hmac-sha256.xml");
650
test_create_signature_enveloping(sha1, hmacSha256, null,
651
getSecretKey("secret".getBytes("ASCII")), sks, false, true);
652
System.out.println();
653
}
654
655
static void test_create_signature_enveloping_hmac_sha224()
656
throws Exception {
657
System.out.println("* Generating signature-enveloping-hmac-sha224.xml");
658
test_create_signature_enveloping(sha1, hmacSha224, null,
659
getSecretKey("secret".getBytes("ASCII")), sks, false, true);
660
System.out.println();
661
}
662
663
static void test_create_signature_enveloping_hmac_sha384()
664
throws Exception {
665
System.out.println("* Generating signature-enveloping-hmac-sha384.xml");
666
test_create_signature_enveloping(sha1, hmacSha384, null,
667
getSecretKey("secret".getBytes("ASCII")), sks, false, true);
668
System.out.println();
669
}
670
671
static void test_create_signature_enveloping_hmac_sha512()
672
throws Exception {
673
System.out.println("* Generating signature-enveloping-hmac-sha512.xml");
674
test_create_signature_enveloping(sha1, hmacSha512, null,
675
getSecretKey("secret".getBytes("ASCII")), sks, false, true);
676
System.out.println();
677
}
678
679
static void test_create_signature_enveloping_rsa() throws Exception {
680
System.out.println("* Generating signature-enveloping-rsa.xml");
681
test_create_signature_enveloping(sha1, rsaSha1, rsa,
682
getPrivateKey("RSA", 512), kvks, false, false);
683
System.out.println();
684
}
685
686
static void test_create_signature_enveloping_sha384_rsa_sha256()
687
throws Exception {
688
System.out.println("* Generating signature-enveloping-sha384-rsa_sha256.xml");
689
test_create_signature_enveloping(sha384, rsaSha256, rsa,
690
getPrivateKey("RSA", 512), kvks, false, false);
691
System.out.println();
692
}
693
694
static void test_create_signature_enveloping_sha224_rsa_sha256()
695
throws Exception {
696
System.out.println("* Generating signature-enveloping-sha224-rsa_sha256.xml");
697
test_create_signature_enveloping(sha224, rsaSha256, rsa,
698
getPrivateKey("RSA", 512), kvks, false, false);
699
System.out.println();
700
}
701
702
static void test_create_signature_enveloping_sha3_224_rsa_sha256()
703
throws Exception {
704
System.out.println("* Generating signature-enveloping-sha3_224-rsa_sha256.xml");
705
test_create_signature_enveloping(sha3_224, rsaSha256, rsa,
706
getPrivateKey("RSA", 512), kvks, false, false);
707
System.out.println();
708
}
709
710
static void test_create_signature_enveloping_sha3_256_rsa_sha256()
711
throws Exception {
712
System.out.println("* Generating signature-enveloping-sha3_256-rsa_sha256.xml");
713
test_create_signature_enveloping(sha3_256, rsaSha256, rsa,
714
getPrivateKey("RSA", 512), kvks, false, false);
715
System.out.println();
716
}
717
718
static void test_create_signature_enveloping_sha3_384_rsa_sha256()
719
throws Exception {
720
System.out.println("* Generating signature-enveloping-sha3_384-rsa_sha256.xml");
721
test_create_signature_enveloping(sha3_384, rsaSha256, rsa,
722
getPrivateKey("RSA", 512), kvks, false, false);
723
System.out.println();
724
}
725
726
static void test_create_signature_enveloping_sha3_512_rsa_sha256()
727
throws Exception {
728
System.out.println("* Generating signature-enveloping-sha3_512-rsa_sha256.xml");
729
test_create_signature_enveloping(sha3_512, rsaSha256, rsa,
730
getPrivateKey("RSA", 512), kvks, false, false);
731
System.out.println();
732
}
733
734
static void test_create_signature_enveloping_sha512_rsa_sha384()
735
throws Exception {
736
System.out.println("* Generating signature-enveloping-sha512-rsa_sha384.xml");
737
test_create_signature_enveloping(sha512, rsaSha384, rsa1024,
738
getPrivateKey("RSA", 1024), kvks, false, true);
739
System.out.println();
740
}
741
742
static void test_create_signature_enveloping_sha512_rsa_sha224()
743
throws Exception {
744
System.out.println("* Generating signature-enveloping-sha512-rsa_sha224.xml");
745
test_create_signature_enveloping(sha512, rsaSha224, rsa1024,
746
getPrivateKey("RSA", 1024), kvks, false, true);
747
System.out.println();
748
}
749
750
static void test_create_signature_enveloping_sha512_rsa_sha512()
751
throws Exception {
752
System.out.println("* Generating signature-enveloping-sha512-rsa_sha512.xml");
753
test_create_signature_enveloping(sha512, rsaSha512, rsa1024,
754
getPrivateKey("RSA", 1024), kvks, false, true);
755
System.out.println();
756
}
757
758
static void test_create_signature_enveloping_sha512_rsa_sha1_mgf1()
759
throws Exception {
760
System.out.println("* Generating signature-enveloping-sha512-rsa_sha1_mgf1.xml");
761
test_create_signature_enveloping(sha512, rsaSha1mgf1, rsa1024,
762
getPrivateKey("RSA", 1024), kvks, false, true);
763
System.out.println();
764
}
765
766
static void test_create_signature_enveloping_sha512_rsa_sha224_mgf1()
767
throws Exception {
768
System.out.println("* Generating signature-enveloping-sha512-rsa_sha224_mgf1.xml");
769
test_create_signature_enveloping(sha512, rsaSha224mgf1, rsa1024,
770
getPrivateKey("RSA", 1024), kvks, false, true);
771
System.out.println();
772
}
773
774
static void test_create_signature_enveloping_sha512_rsa_sha256_mgf1()
775
throws Exception {
776
System.out.println("* Generating signature-enveloping-sha512-rsa_sha256_mgf1.xml");
777
test_create_signature_enveloping(sha512, rsaSha256mgf1, rsa1024,
778
getPrivateKey("RSA", 1024), kvks, false, true);
779
System.out.println();
780
}
781
782
static void test_create_signature_enveloping_sha512_rsa_sha384_mgf1()
783
throws Exception {
784
System.out.println("* Generating signature-enveloping-sha512-rsa_sha384_mgf1.xml");
785
test_create_signature_enveloping(sha512, rsaSha384mgf1, rsa1024,
786
getPrivateKey("RSA", 1024), kvks, false, true);
787
System.out.println();
788
}
789
790
static void test_create_signature_enveloping_sha512_rsa_sha512_mgf1()
791
throws Exception {
792
System.out.println("* Generating signature-enveloping-sha512-rsa_sha512_mgf1.xml");
793
test_create_signature_enveloping(sha512, rsaSha512mgf1, rsa2048,
794
getPrivateKey("RSA", 2048), kvks, false, true);
795
System.out.println();
796
}
797
798
static void test_create_signature_enveloping_sha512_rsa_pss()
799
throws Exception {
800
System.out.println("* Generating signature-enveloping-sha512_rsa_pss.xml");
801
test_create_signature_enveloping(sha512, rsaShaPSS, rsa1024,
802
getPrivateKey("RSA", 1024), kvks, false, true);
803
System.out.println();
804
}
805
806
static void test_create_signature_enveloping_p256_sha1() throws Exception {
807
System.out.println("* Generating signature-enveloping-p256-sha1.xml");
808
test_create_signature_enveloping(sha1, ecdsaSha1, p256ki,
809
getECPrivateKey("P256"), kvks, false, true);
810
System.out.println();
811
}
812
813
static void test_create_signature_enveloping_p256_sha224() throws Exception {
814
System.out.println("* Generating signature-enveloping-p256-sha224.xml");
815
test_create_signature_enveloping(sha1, ecdsaSha224, p256ki,
816
getECPrivateKey("P256"), kvks, false, true);
817
System.out.println();
818
}
819
820
static void test_create_signature_enveloping_p256_sha256() throws Exception {
821
System.out.println("* Generating signature-enveloping-p256-sha256.xml");
822
test_create_signature_enveloping(sha1, ecdsaSha256, p256ki,
823
getECPrivateKey("P256"), kvks, false, true);
824
System.out.println();
825
}
826
827
static void test_create_signature_enveloping_p256_sha384() throws Exception {
828
System.out.println("* Generating signature-enveloping-p256-sha384.xml");
829
test_create_signature_enveloping(sha1, ecdsaSha384, p256ki,
830
getECPrivateKey("P256"), kvks, false, true);
831
System.out.println();
832
}
833
834
static void test_create_signature_enveloping_p256_sha512() throws Exception {
835
System.out.println("* Generating signature-enveloping-p256-sha512.xml");
836
test_create_signature_enveloping(sha1, ecdsaSha512, p256ki,
837
getECPrivateKey("P256"), kvks, false, true);
838
System.out.println();
839
}
840
841
static void test_create_signature_enveloping_p384_sha1() throws Exception {
842
System.out.println("* Generating signature-enveloping-p384-sha1.xml");
843
test_create_signature_enveloping(sha1, ecdsaSha1, p384ki,
844
getECPrivateKey("P384"), kvks, false, true);
845
System.out.println();
846
}
847
848
static void test_create_signature_enveloping_p521_sha1() throws Exception {
849
System.out.println("* Generating signature-enveloping-p521-sha1.xml");
850
test_create_signature_enveloping(sha1, ecdsaSha1, p521ki,
851
getECPrivateKey("P521"), kvks, false, true);
852
System.out.println();
853
}
854
855
static void test_create_signature_external_b64_dsa() throws Exception {
856
System.out.println("* Generating signature-external-b64-dsa.xml");
857
test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, true);
858
System.out.println();
859
}
860
861
static void test_create_signature_external_dsa() throws Exception {
862
System.out.println("* Generating signature-external-dsa.xml");
863
test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, false);
864
System.out.println();
865
}
866
867
static void test_create_signature_keyname() throws Exception {
868
System.out.println("* Generating signature-keyname.xml");
869
KeyInfo kn = kifac.newKeyInfo(Collections.singletonList
870
(kifac.newKeyName("user")));
871
test_create_signature_external(dsaSha1, kn, signingKey,
872
new X509KeySelector(ks), false);
873
System.out.println();
874
}
875
876
static void test_create_signature_retrievalmethod_rawx509crt()
877
throws Exception {
878
System.out.println(
879
"* Generating signature-retrievalmethod-rawx509crt.xml");
880
KeyInfo rm = kifac.newKeyInfo(Collections.singletonList
881
(kifac.newRetrievalMethod
882
("certs/user.crt", X509Data.RAW_X509_CERTIFICATE_TYPE, null)));
883
test_create_signature_external(dsaSha1, rm, signingKey,
884
new X509KeySelector(ks), false);
885
System.out.println();
886
}
887
888
static void test_create_signature_x509_crt_crl() throws Exception {
889
System.out.println("* Generating signature-x509-crt-crl.xml");
890
List<Object> xds = new ArrayList<>();
891
CertificateFactory cf = CertificateFactory.getInstance("X.509");
892
xds.add(signingCert);
893
FileInputStream fis = new FileInputStream(CRL);
894
X509CRL crl = (X509CRL) cf.generateCRL(fis);
895
fis.close();
896
xds.add(crl);
897
KeyInfo crt_crl = kifac.newKeyInfo(Collections.singletonList
898
(kifac.newX509Data(xds)));
899
900
test_create_signature_external(dsaSha1, crt_crl, signingKey,
901
new X509KeySelector(ks), false);
902
System.out.println();
903
}
904
905
static void test_create_signature_x509_crt() throws Exception {
906
System.out.println("* Generating signature-x509-crt.xml");
907
KeyInfo crt = kifac.newKeyInfo(Collections.singletonList
908
(kifac.newX509Data(Collections.singletonList(signingCert))));
909
910
test_create_signature_external(dsaSha1, crt, signingKey,
911
new X509KeySelector(ks), false);
912
System.out.println();
913
}
914
915
static void test_create_signature_x509_is() throws Exception {
916
System.out.println("* Generating signature-x509-is.xml");
917
KeyInfo is = kifac.newKeyInfo(Collections.singletonList
918
(kifac.newX509Data(Collections.singletonList
919
(kifac.newX509IssuerSerial
920
("CN=User", new BigInteger("45ef2729", 16))))));
921
test_create_signature_external(dsaSha1, is, signingKey,
922
new X509KeySelector(ks), false);
923
System.out.println();
924
}
925
926
static void test_create_signature_x509_ski() throws Exception {
927
System.out.println("* Generating signature-x509-ski.xml");
928
KeyInfo ski = kifac.newKeyInfo(Collections.singletonList
929
(kifac.newX509Data(Collections.singletonList
930
("keyid".getBytes("ASCII")))));
931
932
test_create_signature_external(dsaSha1, ski, signingKey,
933
KeySelector.singletonKeySelector(validatingKey), false);
934
System.out.println();
935
}
936
937
static void test_create_signature_x509_sn() throws Exception {
938
System.out.println("* Generating signature-x509-sn.xml");
939
KeyInfo sn = kifac.newKeyInfo(Collections.singletonList
940
(kifac.newX509Data(Collections.singletonList("CN=User"))));
941
942
test_create_signature_external(dsaSha1, sn, signingKey,
943
new X509KeySelector(ks), false);
944
System.out.println();
945
}
946
947
static void test_create_signature_reference_dependency() throws Exception {
948
System.out.println("* Generating signature-reference-dependency.xml");
949
// create references
950
List<Reference> refs = Collections.singletonList
951
(fac.newReference("#object-1", sha1));
952
953
// create SignedInfo
954
SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
955
956
// create objects
957
List<XMLObject> objs = new ArrayList<>();
958
959
// Object 1
960
List<Reference> manRefs = Collections.singletonList
961
(fac.newReference("#object-2", sha1));
962
objs.add(fac.newXMLObject(Collections.singletonList
963
(fac.newManifest(manRefs, "manifest-1")), "object-1", null, null));
964
965
// Object 2
966
Document doc = db.newDocument();
967
Element nc = doc.createElementNS(null, "NonCommentandus");
968
nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");
969
nc.appendChild(doc.createComment(" Commentandum "));
970
objs.add(fac.newXMLObject(Collections.singletonList
971
(new DOMStructure(nc)), "object-2", null, null));
972
973
// create XMLSignature
974
XMLSignature sig = fac.newXMLSignature(si, rsa, objs, "signature", null);
975
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
976
977
sig.sign(dsc);
978
979
// dumpDocument(doc, new PrintWriter(System.out));
980
981
DOMValidateContext dvc = new DOMValidateContext
982
(kvks, doc.getDocumentElement());
983
dvc.setProperty("org.jcp.xml.dsig.secureValidation", false);
984
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
985
986
if (sig.equals(sig2) == false) {
987
throw new Exception
988
("Unmarshalled signature is not equal to generated signature");
989
}
990
if (sig2.validate(dvc) == false) {
991
throw new Exception("Validation of generated signature failed");
992
}
993
994
System.out.println();
995
}
996
997
static void test_create_signature_with_attr_in_no_namespace()
998
throws Exception
999
{
1000
System.out.println
1001
("* Generating signature-with-attr-in-no-namespace.xml");
1002
1003
// create references
1004
List<Reference> refs = Collections.singletonList
1005
(fac.newReference("#unknown", sha1));
1006
1007
// create SignedInfo
1008
SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
1009
1010
// create object-1
1011
Document doc = db.newDocument();
1012
Element nc = doc.createElementNS(null, "NonCommentandus");
1013
// add attribute with no namespace
1014
nc.setAttribute("Id", "unknown");
1015
XMLObject obj = fac.newXMLObject(Collections.singletonList
1016
(new DOMStructure(nc)), "object-1", null, null);
1017
1018
// create XMLSignature
1019
XMLSignature sig = fac.newXMLSignature(si, rsa,
1020
Collections.singletonList(obj),
1021
"signature", null);
1022
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
1023
dsc.setIdAttributeNS(nc, null, "Id");
1024
1025
sig.sign(dsc);
1026
1027
// dumpDocument(doc, new PrintWriter(System.out));
1028
1029
DOMValidateContext dvc = new DOMValidateContext
1030
(kvks, doc.getDocumentElement());
1031
dvc.setProperty("org.jcp.xml.dsig.secureValidation", false);
1032
dvc.setIdAttributeNS(nc, null, "Id");
1033
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1034
1035
if (sig.equals(sig2) == false) {
1036
throw new Exception
1037
("Unmarshalled signature is not equal to generated signature");
1038
}
1039
if (sig2.validate(dvc) == false) {
1040
throw new Exception("Validation of generated signature failed");
1041
}
1042
1043
System.out.println();
1044
}
1045
1046
static void test_create_signature_with_empty_id() throws Exception {
1047
System.out.println("* Generating signature-with-empty-id.xml");
1048
1049
// create references
1050
List<Reference> refs = Collections.singletonList
1051
(fac.newReference("#", sha1));
1052
1053
// create SignedInfo
1054
SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
1055
1056
// create object with empty id
1057
Document doc = db.newDocument();
1058
XMLObject obj = fac.newXMLObject(Collections.singletonList
1059
(new DOMStructure(doc.createTextNode("I am the text."))),
1060
"", "text/plain", null);
1061
1062
// create XMLSignature
1063
XMLSignature sig = fac.newXMLSignature(si, rsa,
1064
Collections.singletonList(obj),
1065
"signature", null);
1066
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
1067
sig.sign(dsc);
1068
1069
System.out.println();
1070
}
1071
1072
static void test_create_signature_enveloping_over_doc(String filename,
1073
boolean pass) throws Exception
1074
{
1075
System.out.println("* Generating signature-enveloping-over-doc.xml");
1076
1077
// create reference
1078
Reference ref = fac.newReference("#object", sha256);
1079
1080
// create SignedInfo
1081
SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha256,
1082
Collections.singletonList(ref));
1083
1084
// create object
1085
Document doc = null;
1086
try (FileInputStream fis = new FileInputStream(filename)) {
1087
doc = db.parse(fis);
1088
}
1089
DOMStructure ds = pass ? new DOMStructure(doc.getDocumentElement())
1090
: new DOMStructure(doc);
1091
XMLObject obj = fac.newXMLObject(Collections.singletonList(ds),
1092
"object", null, "UTF-8");
1093
1094
// This creates an enveloping signature over the entire XML Document
1095
XMLSignature sig = fac.newXMLSignature(si, rsa,
1096
Collections.singletonList(obj),
1097
"signature", null);
1098
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 1024), doc);
1099
try {
1100
sig.sign(dsc);
1101
if (!pass) {
1102
// A Document node can only exist at the root of the doc so this
1103
// should fail
1104
throw new Exception("Test unexpectedly passed");
1105
}
1106
} catch (Exception e) {
1107
if (!pass) {
1108
System.out.println("Test failed as expected: " + e);
1109
} else {
1110
throw e;
1111
}
1112
}
1113
1114
if (pass) {
1115
DOMValidateContext dvc = new DOMValidateContext
1116
(getPublicKey("RSA", 1024), doc.getDocumentElement());
1117
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1118
1119
if (sig.equals(sig2) == false) {
1120
throw new Exception
1121
("Unmarshalled signature is not equal to generated signature");
1122
}
1123
if (sig2.validate(dvc) == false) {
1124
throw new Exception("Validation of generated signature failed");
1125
}
1126
}
1127
1128
System.out.println();
1129
}
1130
1131
static void test_create_signature_enveloping_dom_level1() throws Exception {
1132
System.out.println("* Generating signature-enveloping-dom-level1.xml");
1133
1134
// create reference
1135
Reference ref = fac.newReference("#object", sha256);
1136
1137
// create SignedInfo
1138
SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha256,
1139
Collections.singletonList(ref));
1140
1141
// create object using DOM Level 1 methods
1142
Document doc = db.newDocument();
1143
Element child = doc.createElement("Child");
1144
child.setAttribute("Version", "1.0");
1145
child.setAttribute("Id", "child");
1146
child.setIdAttribute("Id", true);
1147
child.appendChild(doc.createComment("Comment"));
1148
XMLObject obj = fac.newXMLObject(
1149
Collections.singletonList(new DOMStructure(child)),
1150
"object", null, "UTF-8");
1151
1152
XMLSignature sig = fac.newXMLSignature(si, rsa,
1153
Collections.singletonList(obj),
1154
"signature", null);
1155
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 1024), doc);
1156
sig.sign(dsc);
1157
1158
DOMValidateContext dvc = new DOMValidateContext
1159
(getPublicKey("RSA", 1024), doc.getDocumentElement());
1160
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1161
1162
if (sig.equals(sig2) == false) {
1163
throw new Exception
1164
("Unmarshalled signature is not equal to generated signature");
1165
}
1166
if (sig2.validate(dvc) == false) {
1167
throw new Exception("Validation of generated signature failed");
1168
}
1169
1170
System.out.println();
1171
}
1172
1173
static void test_create_signature() throws Exception {
1174
System.out.println("* Generating signature.xml");
1175
1176
// create references
1177
List<Reference> refs = new ArrayList<>();
1178
1179
// Reference 1
1180
refs.add(fac.newReference(STYLESHEET, sha1));
1181
1182
// Reference 2
1183
refs.add(fac.newReference
1184
(STYLESHEET_B64,
1185
sha1, Collections.singletonList
1186
(fac.newTransform(Transform.BASE64,
1187
(TransformParameterSpec) null)), null, null));
1188
1189
// Reference 3
1190
refs.add(fac.newReference("#object-1", sha1, Collections.singletonList
1191
(fac.newTransform(Transform.XPATH,
1192
new XPathFilterParameterSpec("self::text()"))),
1193
XMLObject.TYPE, null));
1194
1195
// Reference 4
1196
String expr = "\n"
1197
+ " ancestor-or-self::dsig:SignedInfo " + "\n"
1198
+ " and " + "\n"
1199
+ " count(ancestor-or-self::dsig:Reference | " + "\n"
1200
+ " here()/ancestor::dsig:Reference[1]) > " + "\n"
1201
+ " count(ancestor-or-self::dsig:Reference) " + "\n"
1202
+ " or " + "\n"
1203
+ " count(ancestor-or-self::node() | " + "\n"
1204
+ " id('notaries')) = " + "\n"
1205
+ " count(ancestor-or-self::node()) " + "\n";
1206
1207
XPathFilterParameterSpec xfp = new XPathFilterParameterSpec(expr,
1208
Collections.singletonMap("dsig", XMLSignature.XMLNS));
1209
refs.add(fac.newReference("", sha1, Collections.singletonList
1210
(fac.newTransform(Transform.XPATH, xfp)),
1211
XMLObject.TYPE, null));
1212
1213
// Reference 5
1214
refs.add(fac.newReference("#object-2", sha1, Collections.singletonList
1215
(fac.newTransform
1216
(Transform.BASE64, (TransformParameterSpec) null)),
1217
XMLObject.TYPE, null));
1218
1219
// Reference 6
1220
refs.add(fac.newReference
1221
("#manifest-1", sha1, null, Manifest.TYPE, null));
1222
1223
// Reference 7
1224
refs.add(fac.newReference("#signature-properties-1", sha1, null,
1225
SignatureProperties.TYPE, null));
1226
1227
// Reference 8
1228
List<Transform> transforms = new ArrayList<>();
1229
transforms.add(fac.newTransform
1230
(Transform.ENVELOPED, (TransformParameterSpec) null));
1231
refs.add(fac.newReference("", sha1, transforms, null, null));
1232
1233
// Reference 9
1234
transforms.add(fac.newTransform
1235
(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
1236
(TransformParameterSpec) null));
1237
refs.add(fac.newReference("", sha1, transforms, null, null));
1238
1239
// Reference 10
1240
Transform env = fac.newTransform
1241
(Transform.ENVELOPED, (TransformParameterSpec) null);
1242
refs.add(fac.newReference("#xpointer(/)",
1243
sha1, Collections.singletonList(env), null, null));
1244
1245
// Reference 11
1246
transforms.clear();
1247
transforms.add(fac.newTransform
1248
(Transform.ENVELOPED, (TransformParameterSpec) null));
1249
transforms.add(fac.newTransform
1250
(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
1251
(TransformParameterSpec) null));
1252
refs.add(fac.newReference("#xpointer(/)", sha1, transforms,
1253
null, null));
1254
1255
// Reference 12
1256
refs.add
1257
(fac.newReference("#object-3", sha1, null, XMLObject.TYPE, null));
1258
1259
// Reference 13
1260
Transform withComments = fac.newTransform
1261
(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
1262
(TransformParameterSpec) null);
1263
refs.add(fac.newReference("#object-3", sha1,
1264
Collections.singletonList(withComments), XMLObject.TYPE, null));
1265
1266
// Reference 14
1267
refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, null,
1268
XMLObject.TYPE, null));
1269
1270
// Reference 15
1271
withComments = fac.newTransform
1272
(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
1273
(TransformParameterSpec) null);
1274
refs.add(fac.newReference("#xpointer(id('object-3'))", sha1,
1275
Collections.singletonList(withComments), XMLObject.TYPE, null));
1276
1277
// Reference 16
1278
refs.add(fac.newReference("#reference-2", sha1));
1279
1280
// Reference 17
1281
refs.add(fac.newReference("#manifest-reference-1", sha1, null,
1282
null, "reference-1"));
1283
1284
// Reference 18
1285
refs.add(fac.newReference("#reference-1", sha1, null, null,
1286
"reference-2"));
1287
1288
// create SignedInfo
1289
SignedInfo si = fac.newSignedInfo(withoutComments, dsaSha1, refs);
1290
1291
// create keyinfo
1292
XPathFilterParameterSpec xpf = new XPathFilterParameterSpec(
1293
"ancestor-or-self::dsig:X509Data",
1294
Collections.singletonMap("dsig", XMLSignature.XMLNS));
1295
RetrievalMethod rm = kifac.newRetrievalMethod("#object-4",
1296
X509Data.TYPE, Collections.singletonList(fac.newTransform
1297
(Transform.XPATH, xpf)));
1298
KeyInfo ki = kifac.newKeyInfo(Collections.singletonList(rm), null);
1299
1300
Document doc = db.newDocument();
1301
1302
// create objects
1303
List<XMLObject> objs = new ArrayList<>();
1304
1305
// Object 1
1306
objs.add(fac.newXMLObject(Collections.singletonList
1307
(new DOMStructure(doc.createTextNode("I am the text."))),
1308
"object-1", "text/plain", null));
1309
1310
// Object 2
1311
objs.add(fac.newXMLObject(Collections.singletonList
1312
(new DOMStructure(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="))),
1313
"object-2", "text/plain", Transform.BASE64));
1314
1315
// Object 3
1316
Element nc = doc.createElementNS(null, "NonCommentandus");
1317
nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");
1318
nc.appendChild(doc.createComment(" Commentandum "));
1319
objs.add(fac.newXMLObject(Collections.singletonList
1320
(new DOMStructure(nc)), "object-3", null, null));
1321
1322
// Manifest
1323
List<Reference> manRefs = new ArrayList<>();
1324
1325
// Manifest Reference 1
1326
manRefs.add(fac.newReference(STYLESHEET,
1327
sha1, null, null, "manifest-reference-1"));
1328
1329
// Manifest Reference 2
1330
manRefs.add(fac.newReference("#reference-1", sha1));
1331
1332
// Manifest Reference 3
1333
List<Transform> manTrans = new ArrayList<>();
1334
Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));
1335
Node xslElem = docxslt.getDocumentElement();
1336
1337
manTrans.add(fac.newTransform(Transform.XSLT,
1338
new XSLTTransformParameterSpec(new DOMStructure(xslElem))));
1339
manTrans.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE,
1340
(TransformParameterSpec) null));
1341
manRefs.add(fac.newReference("#notaries", sha1, manTrans, null, null));
1342
1343
objs.add(fac.newXMLObject(Collections.singletonList
1344
(fac.newManifest(manRefs, "manifest-1")), null, null, null));
1345
1346
// SignatureProperties
1347
Element sa = doc.createElementNS("urn:demo", "SignerAddress");
1348
sa.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:demo");
1349
Element ip = doc.createElementNS("urn:demo", "IP");
1350
ip.appendChild(doc.createTextNode("192.168.21.138"));
1351
sa.appendChild(ip);
1352
SignatureProperty sp = fac.newSignatureProperty
1353
(Collections.singletonList(new DOMStructure(sa)),
1354
"#signature", null);
1355
SignatureProperties sps = fac.newSignatureProperties
1356
(Collections.singletonList(sp), "signature-properties-1");
1357
objs.add(fac.newXMLObject(Collections.singletonList(sps), null,
1358
null, null));
1359
1360
// Object 4
1361
List<Object> xds = new ArrayList<>();
1362
xds.add("CN=User");
1363
xds.add(kifac.newX509IssuerSerial
1364
("CN=User", new BigInteger("45ef2729", 16)));
1365
xds.add(signingCert);
1366
objs.add(fac.newXMLObject(Collections.singletonList
1367
(kifac.newX509Data(xds)), "object-4", null, null));
1368
1369
// create XMLSignature
1370
XMLSignature sig = fac.newXMLSignature(si, ki, objs, "signature", null);
1371
1372
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1373
dbf.setNamespaceAware(true);
1374
dbf.setValidating(false);
1375
Document envDoc = dbf.newDocumentBuilder().parse
1376
(new FileInputStream(ENVELOPE));
1377
Element ys = (Element)
1378
envDoc.getElementsByTagName("YoursSincerely").item(0);
1379
1380
DOMSignContext dsc = new DOMSignContext(signingKey, ys);
1381
dsc.setURIDereferencer(httpUd);
1382
1383
sig.sign(dsc);
1384
1385
// StringWriter sw = new StringWriter();
1386
// dumpDocument(envDoc, sw);
1387
1388
NodeList nl =
1389
envDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
1390
if (nl.getLength() == 0) {
1391
throw new Exception("Couldn't find signature Element");
1392
}
1393
Element sigElement = (Element) nl.item(0);
1394
1395
DOMValidateContext dvc = new DOMValidateContext
1396
(new X509KeySelector(ks), sigElement);
1397
dvc.setURIDereferencer(httpUd);
1398
File f = new File(
1399
System.getProperty("dir.test.vector.baltimore") +
1400
System.getProperty("file.separator") +
1401
"merlin-xmldsig-twenty-three" +
1402
System.getProperty("file.separator"));
1403
dvc.setBaseURI(f.toURI().toString());
1404
1405
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1406
1407
if (sig.equals(sig2) == false) {
1408
throw new Exception
1409
("Unmarshalled signature is not equal to generated signature");
1410
}
1411
if (sig2.validate(dvc) == false) {
1412
throw new Exception("Validation of generated signature failed");
1413
}
1414
System.out.println();
1415
}
1416
1417
private static void dumpDocument(Document doc, Writer w) throws Exception {
1418
TransformerFactory tf = TransformerFactory.newInstance();
1419
Transformer trans = tf.newTransformer();
1420
// trans.setOutputProperty(OutputKeys.INDENT, "yes");
1421
trans.transform(new DOMSource(doc), new StreamResult(w));
1422
}
1423
1424
private static void test_create_signature_external
1425
(SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks,
1426
boolean b64) throws Exception {
1427
1428
// create reference
1429
Reference ref;
1430
if (b64) {
1431
ref = fac.newReference
1432
(STYLESHEET_B64,
1433
sha1, Collections.singletonList
1434
(fac.newTransform(Transform.BASE64,
1435
(TransformParameterSpec) null)), null, null);
1436
} else {
1437
ref = fac.newReference(STYLESHEET, sha1);
1438
}
1439
1440
// create SignedInfo
1441
SignedInfo si = fac.newSignedInfo(withoutComments, sm,
1442
Collections.singletonList(ref));
1443
1444
Document doc = db.newDocument();
1445
1446
// create XMLSignature
1447
XMLSignature sig = fac.newXMLSignature(si, ki);
1448
1449
DOMSignContext dsc = new DOMSignContext(signingKey, doc);
1450
dsc.setURIDereferencer(httpUd);
1451
1452
sig.sign(dsc);
1453
1454
DOMValidateContext dvc = new DOMValidateContext
1455
(ks, doc.getDocumentElement());
1456
File f = new File(DATA_DIR);
1457
dvc.setURIDereferencer(httpUd);
1458
1459
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1460
1461
if (sig.equals(sig2) == false) {
1462
throw new Exception
1463
("Unmarshalled signature is not equal to generated signature");
1464
}
1465
if (sig2.validate(dvc) == false) {
1466
throw new Exception("Validation of generated signature failed");
1467
}
1468
}
1469
1470
private static void test_create_signature_enveloping
1471
(DigestMethod dm, SignatureMethod sm, KeyInfo ki, Key signingKey,
1472
KeySelector ks, boolean b64, boolean secVal) throws Exception {
1473
1474
// create reference
1475
Reference ref;
1476
if (b64) {
1477
ref = fac.newReference("#object", dm, Collections.singletonList
1478
(fac.newTransform(Transform.BASE64,
1479
(TransformParameterSpec) null)), null, null);
1480
} else {
1481
ref = fac.newReference("#object", dm);
1482
}
1483
1484
// create SignedInfo
1485
SignedInfo si = fac.newSignedInfo(withoutComments, sm,
1486
Collections.singletonList(ref));
1487
1488
Document doc = db.newDocument();
1489
// create Objects
1490
String text = b64 ? "c29tZSB0ZXh0" : "some text";
1491
XMLObject obj = fac.newXMLObject(Collections.singletonList
1492
(new DOMStructure(doc.createTextNode(text))),
1493
"object", null, null);
1494
1495
// create XMLSignature
1496
XMLSignature sig = fac.newXMLSignature
1497
(si, ki, Collections.singletonList(obj), null, null);
1498
1499
DOMSignContext dsc = new DOMSignContext(signingKey, doc);
1500
1501
sig.sign(dsc);
1502
1503
// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1504
1505
DOMValidateContext dvc = new DOMValidateContext
1506
(ks, doc.getDocumentElement());
1507
dvc.setProperty("org.jcp.xml.dsig.secureValidation", secVal);
1508
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1509
1510
if (sig.equals(sig2) == false) {
1511
throw new Exception
1512
("Unmarshalled signature is not equal to generated signature");
1513
}
1514
if (sig2.validate(dvc) == false) {
1515
throw new Exception("Validation of generated signature failed");
1516
}
1517
}
1518
1519
static void test_create_exc_signature() throws Exception {
1520
System.out.println("* Generating exc_signature.xml");
1521
List<Reference> refs = new ArrayList<>(4);
1522
1523
// create reference 1
1524
refs.add(fac.newReference
1525
("#xpointer(id('to-be-signed'))", sha1,
1526
Collections.singletonList
1527
(fac.newTransform(CanonicalizationMethod.EXCLUSIVE,
1528
(TransformParameterSpec) null)),
1529
null, null));
1530
1531
// create reference 2
1532
List<String> prefixList = new ArrayList<>(2);
1533
prefixList.add("bar");
1534
prefixList.add("#default");
1535
ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);
1536
refs.add(fac.newReference
1537
("#xpointer(id('to-be-signed'))", sha1,
1538
Collections.singletonList
1539
(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)),
1540
null, null));
1541
1542
// create reference 3
1543
refs.add(fac.newReference
1544
("#xpointer(id('to-be-signed'))", sha1,
1545
Collections.singletonList(fac.newTransform
1546
(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
1547
(TransformParameterSpec) null)),
1548
null, null));
1549
1550
// create reference 4
1551
prefixList = new ArrayList<>(2);
1552
prefixList.add("bar");
1553
prefixList.add("#default");
1554
params = new ExcC14NParameterSpec(prefixList);
1555
refs.add(fac.newReference
1556
("#xpointer(id('to-be-signed'))", sha1,
1557
Collections.singletonList(fac.newTransform
1558
(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)),
1559
null, null));
1560
1561
// create SignedInfo
1562
SignedInfo si = fac.newSignedInfo(
1563
fac.newCanonicalizationMethod
1564
(CanonicalizationMethod.EXCLUSIVE,
1565
(C14NMethodParameterSpec) null),
1566
dsaSha1, refs);
1567
1568
// create KeyInfo
1569
List<XMLStructure> kits = new ArrayList<>(2);
1570
kits.add(kifac.newKeyValue(validatingKey));
1571
KeyInfo ki = kifac.newKeyInfo(kits);
1572
1573
// create Objects
1574
Document doc = db.newDocument();
1575
Element baz = doc.createElementNS("urn:bar", "bar:Baz");
1576
Comment com = doc.createComment(" comment ");
1577
baz.appendChild(com);
1578
XMLObject obj = fac.newXMLObject(Collections.singletonList
1579
(new DOMStructure(baz)), "to-be-signed", null, null);
1580
1581
// create XMLSignature
1582
XMLSignature sig = fac.newXMLSignature
1583
(si, ki, Collections.singletonList(obj), null, null);
1584
1585
Element foo = doc.createElementNS("urn:foo", "Foo");
1586
foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");
1587
foo.setAttributeNS
1588
("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");
1589
doc.appendChild(foo);
1590
1591
DOMSignContext dsc = new DOMSignContext(signingKey, foo);
1592
dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");
1593
1594
sig.sign(dsc);
1595
1596
// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1597
1598
DOMValidateContext dvc = new DOMValidateContext
1599
(new KeySelectors.KeyValueKeySelector(), foo.getLastChild());
1600
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1601
1602
if (sig.equals(sig2) == false) {
1603
throw new Exception
1604
("Unmarshalled signature is not equal to generated signature");
1605
}
1606
if (sig2.validate(dvc) == false) {
1607
throw new Exception("Validation of generated signature failed");
1608
}
1609
System.out.println();
1610
}
1611
1612
static void test_create_sign_spec() throws Exception {
1613
System.out.println("* Generating sign-spec.xml");
1614
List<Reference> refs = new ArrayList<>(2);
1615
1616
// create reference 1
1617
List<XPathType> types = new ArrayList<>(3);
1618
types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT));
1619
types.add(new XPathType(" //NotToBeSigned ",
1620
XPathType.Filter.SUBTRACT));
1621
types.add(new XPathType(" //ReallyToBeSigned ",
1622
XPathType.Filter.UNION));
1623
XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);
1624
refs.add(fac.newReference("", sha1,
1625
Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)),
1626
null, null));
1627
1628
// create reference 2
1629
List<Transform> trans2 = new ArrayList<>(2);
1630
trans2.add(fac.newTransform(Transform.ENVELOPED,
1631
(TransformParameterSpec) null));
1632
XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec
1633
(Collections.singletonList
1634
(new XPathType(" / ", XPathType.Filter.UNION)));
1635
trans2.add(fac.newTransform(Transform.XPATH2, xp2));
1636
refs.add(fac.newReference("#signature-value", sha1, trans2, null, null));
1637
1638
// create SignedInfo
1639
SignedInfo si = fac.newSignedInfo(
1640
fac.newCanonicalizationMethod
1641
(CanonicalizationMethod.INCLUSIVE,
1642
(C14NMethodParameterSpec) null),
1643
dsaSha1, refs);
1644
1645
// create KeyInfo
1646
List<XMLStructure> kits = new ArrayList<>(2);
1647
kits.add(kifac.newKeyValue(validatingKey));
1648
List<Object> xds = new ArrayList<>(2);
1649
xds.add("CN=User");
1650
xds.add(signingCert);
1651
kits.add(kifac.newX509Data(xds));
1652
KeyInfo ki = kifac.newKeyInfo(kits);
1653
1654
// create XMLSignature
1655
XMLSignature sig = fac.newXMLSignature
1656
(si, ki, null, null, "signature-value");
1657
1658
Document doc = db.newDocument();
1659
Element tbs1 = doc.createElementNS(null, "ToBeSigned");
1660
Comment tbs1Com = doc.createComment(" comment ");
1661
Element tbs1Data = doc.createElementNS(null, "Data");
1662
Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned");
1663
Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned");
1664
Comment tbs1rtbsCom = doc.createComment(" comment ");
1665
Element tbs1rtbsData = doc.createElementNS(null, "Data");
1666
tbs1rtbs.appendChild(tbs1rtbsCom);
1667
tbs1rtbs.appendChild(tbs1rtbsData);
1668
tbs1ntbs.appendChild(tbs1rtbs);
1669
tbs1.appendChild(tbs1Com);
1670
tbs1.appendChild(tbs1Data);
1671
tbs1.appendChild(tbs1ntbs);
1672
1673
Element tbs2 = doc.createElementNS(null, "ToBeSigned");
1674
Element tbs2Data = doc.createElementNS(null, "Data");
1675
Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned");
1676
Element tbs2ntbsData = doc.createElementNS(null, "Data");
1677
tbs2ntbs.appendChild(tbs2ntbsData);
1678
tbs2.appendChild(tbs2Data);
1679
tbs2.appendChild(tbs2ntbs);
1680
1681
Element document = doc.createElementNS(null, "Document");
1682
document.appendChild(tbs1);
1683
document.appendChild(tbs2);
1684
doc.appendChild(document);
1685
1686
DOMSignContext dsc = new DOMSignContext(signingKey, document);
1687
1688
sig.sign(dsc);
1689
1690
// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1691
1692
DOMValidateContext dvc = new DOMValidateContext
1693
(new KeySelectors.KeyValueKeySelector(), document.getLastChild());
1694
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1695
1696
if (sig.equals(sig2) == false) {
1697
throw new Exception
1698
("Unmarshalled signature is not equal to generated signature");
1699
}
1700
if (sig2.validate(dvc) == false) {
1701
throw new Exception("Validation of generated signature failed");
1702
}
1703
System.out.println();
1704
}
1705
1706
// Only print if there is an error.
1707
static void test_create_detached_signature(
1708
String canonicalizationMethod, String signatureMethod,
1709
String digestMethod, String transform, KeyInfoType keyInfo,
1710
Content contentType, int port, boolean expectedFailure,
1711
Class expectedException) {
1712
1713
String title = "\nTest detached signature:"
1714
+ "\n Canonicalization method: " + canonicalizationMethod
1715
+ "\n Signature method: " + signatureMethod
1716
+ "\n Transform: " + transform
1717
+ "\n Digest method: " + digestMethod
1718
+ "\n KeyInfoType: " + keyInfo
1719
+ "\n Content type: " + contentType
1720
+ "\n Expected failure: " + (expectedFailure ? "yes" : "no")
1721
+ "\n Expected exception: " + (expectedException == null ?
1722
"no" : expectedException.getName());
1723
1724
try {
1725
boolean success = test_create_detached_signature0(
1726
canonicalizationMethod,
1727
signatureMethod,
1728
digestMethod,
1729
transform,
1730
keyInfo,
1731
contentType,
1732
port);
1733
1734
if (success && expectedFailure) {
1735
System.out.println(title);
1736
System.out.println("Signature validation unexpectedly passed");
1737
result = false;
1738
} else if (!success && !expectedFailure) {
1739
System.out.println(title);
1740
System.out.println("Signature validation unexpectedly failed");
1741
result = false;
1742
} else if (expectedException != null) {
1743
System.out.println(title);
1744
System.out.println("Expected " + expectedException
1745
+ " not thrown");
1746
result = false;
1747
}
1748
} catch (Exception e) {
1749
if (expectedException == null
1750
|| !e.getClass().isAssignableFrom(expectedException)) {
1751
System.out.println(title);
1752
System.out.println("Unexpected exception: " + e);
1753
e.printStackTrace(System.out);
1754
result = false;
1755
}
1756
}
1757
}
1758
1759
// Print out as little as possible. This method will be called many times.
1760
static boolean test_create_detached_signature0(String canonicalizationMethod,
1761
String signatureMethod, String digestMethod, String transform,
1762
KeyInfoType keyInfo, Content contentType, int port)
1763
throws Exception {
1764
1765
System.out.print("-S");
1766
System.out.flush();
1767
1768
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1769
dbf.setNamespaceAware(true);
1770
dbf.setValidating(false);
1771
1772
// Create SignedInfo
1773
DigestMethod dm = fac.newDigestMethod(digestMethod, null);
1774
1775
List transformList = null;
1776
if (transform != null) {
1777
TransformParameterSpec params = null;
1778
switch (transform) {
1779
case Transform.XPATH:
1780
params = new XPathFilterParameterSpec("//.");
1781
break;
1782
case Transform.XPATH2:
1783
params = new XPathFilter2ParameterSpec(
1784
Collections.singletonList(new XPathType("//.",
1785
XPathType.Filter.INTERSECT)));
1786
break;
1787
case Transform.XSLT:
1788
Element element = dbf.newDocumentBuilder()
1789
.parse(new ByteArrayInputStream(xslt.getBytes()))
1790
.getDocumentElement();
1791
DOMStructure stylesheet = new DOMStructure(element);
1792
params = new XSLTTransformParameterSpec(stylesheet);
1793
break;
1794
}
1795
transformList = Collections.singletonList(fac.newTransform(
1796
transform, params));
1797
}
1798
1799
String url = String.format("http://localhost:%d/%s", port, contentType);
1800
List refs = Collections.singletonList(fac.newReference(url, dm,
1801
transformList, null, null));
1802
1803
CanonicalizationMethod cm = fac.newCanonicalizationMethod(
1804
canonicalizationMethod, (C14NMethodParameterSpec) null);
1805
1806
SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
1807
1808
Key[] pair = getCachedKeys(signatureMethod);
1809
Key signingKey = pair[0];
1810
Key validationKey = pair[1];
1811
1812
SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
1813
1814
// Create KeyInfo
1815
KeyInfoFactory kif = fac.getKeyInfoFactory();
1816
List list = null;
1817
if (keyInfo == KeyInfoType.KeyValue) {
1818
if (validationKey instanceof PublicKey) {
1819
KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
1820
list = Collections.singletonList(kv);
1821
}
1822
} else if (keyInfo == KeyInfoType.x509data) {
1823
list = Collections.singletonList(
1824
kif.newX509Data(Collections.singletonList("cn=Test")));
1825
} else if (keyInfo == KeyInfoType.KeyName) {
1826
list = Collections.singletonList(kif.newKeyName("Test"));
1827
} else {
1828
throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
1829
}
1830
KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
1831
1832
// Create an empty doc for detached signature
1833
Document doc = dbf.newDocumentBuilder().newDocument();
1834
DOMSignContext xsc = new DOMSignContext(signingKey, doc);
1835
1836
// Generate signature
1837
XMLSignature signature = fac.newXMLSignature(si, ki);
1838
signature.sign(xsc);
1839
1840
// Save signature
1841
String signatureString;
1842
try (StringWriter writer = new StringWriter()) {
1843
TransformerFactory tf = TransformerFactory.newInstance();
1844
Transformer trans = tf.newTransformer();
1845
Node parent = xsc.getParent();
1846
trans.transform(new DOMSource(parent), new StreamResult(writer));
1847
signatureString = writer.toString();
1848
}
1849
1850
System.out.print("V");
1851
System.out.flush();
1852
try (ByteArrayInputStream bis = new ByteArrayInputStream(
1853
signatureString.getBytes())) {
1854
doc = dbf.newDocumentBuilder().parse(bis);
1855
}
1856
1857
NodeList nodeLst = doc.getElementsByTagName("Signature");
1858
Node node = nodeLst.item(0);
1859
if (node == null) {
1860
throw new RuntimeException("Couldn't find Signature element");
1861
}
1862
if (!(node instanceof Element)) {
1863
throw new RuntimeException("Unexpected node type");
1864
}
1865
Element sig = (Element) node;
1866
1867
// Validate signature
1868
DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
1869
vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
1870
signature = fac.unmarshalXMLSignature(vc);
1871
1872
boolean success = signature.validate(vc);
1873
if (!success) {
1874
System.out.print("x");
1875
System.out.flush();
1876
return false;
1877
}
1878
1879
success = signature.getSignatureValue().validate(vc);
1880
if (!success) {
1881
System.out.print("X");
1882
System.out.flush();
1883
return false;
1884
}
1885
1886
return true;
1887
}
1888
1889
private static Key[] getCachedKeys(String signatureMethod) {
1890
return cachedKeys.computeIfAbsent(signatureMethod, sm -> {
1891
try {
1892
System.out.print("<create keys for " + sm + ">");
1893
System.out.flush();
1894
if (sm.contains("#hmac-")) {
1895
// http://...#hmac-sha1 -> hmac-sha1 -> hmacsha1
1896
String algName = sm
1897
.substring(sm.indexOf('#') + 1)
1898
.replace("-", "");
1899
KeyGenerator kg = KeyGenerator.getInstance(algName);
1900
Key signingKey = kg.generateKey();
1901
return new Key[] { signingKey, signingKey};
1902
} else {
1903
KeyPairGenerator kpg;
1904
if (sm.contains("#rsa-")
1905
|| sm.contains("-rsa-MGF1")) {
1906
kpg = KeyPairGenerator.getInstance("RSA");
1907
kpg.initialize(
1908
sm.contains("#sha512-rsa-MGF1") ? 2048 : 1024);
1909
} else if (sm.contains("#dsa-")) {
1910
kpg = KeyPairGenerator.getInstance("DSA");
1911
kpg.initialize(1024);
1912
} else if (sm.contains("#ecdsa-")) {
1913
kpg = KeyPairGenerator.getInstance("EC");
1914
kpg.initialize(256);
1915
} else {
1916
throw new RuntimeException("Unsupported signature algorithm");
1917
}
1918
KeyPair kp = kpg.generateKeyPair();
1919
return new Key[] { kp.getPrivate(), kp.getPublic()};
1920
}
1921
} catch (NoSuchAlgorithmException e) {
1922
throw new AssertionError("Should not happen", e);
1923
}
1924
});
1925
}
1926
1927
private static final String DSA_Y =
1928
"070662842167565771936588335128634396171789331656318483584455493822" +
1929
"400811200853331373030669235424928346190274044631949560438023934623" +
1930
"71310375123430985057160";
1931
private static final String DSA_P =
1932
"013232376895198612407547930718267435757728527029623408872245156039" +
1933
"757713029036368719146452186041204237350521785240337048752071462798" +
1934
"273003935646236777459223";
1935
private static final String DSA_Q =
1936
"0857393771208094202104259627990318636601332086981";
1937
private static final String DSA_G =
1938
"054216440574364751416096484883257051280474283943804743768346673007" +
1939
"661082626139005426812890807137245973106730741193551360857959820973" +
1940
"90670890367185141189796";
1941
private static final String DSA_X =
1942
"0527140396812450214498055937934275626078768840117";
1943
private static final String DSA_2048_Y =
1944
"15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928";
1945
private static final String DSA_2048_P =
1946
"18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359";
1947
private static final String DSA_2048_Q =
1948
"19689526866605154788513693571065914024068069442724893395618704484701";
1949
private static final String DSA_2048_G =
1950
"2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430";
1951
private static final String DSA_2048_X =
1952
"14562787764977288900757387442281559936279834964901963465277698843172";
1953
private static final String RSA_MOD =
1954
"010800185049102889923150759252557522305032794699952150943573164381" +
1955
"936603255999071981574575044810461362008102247767482738822150129277" +
1956
"490998033971789476107463";
1957
private static final String RSA_PRIV =
1958
"016116973584421969795445996229612671947635798429212816611707210835" +
1959
"915586591340598683996088487065438751488342251960069575392056288063" +
1960
"6800379454345804879553";
1961
private static final String RSA_PUB = "065537";
1962
private static final String RSA_1024_MOD = "098871307553789439961130765" +
1963
"909423744508062468450669519128736624058048856940468016843888594585" +
1964
"322862378444314635412341974900625010364163960238734457710620107530" +
1965
"573945081856371709138380902553309075505688814637544923038853658690" +
1966
"857672483016239697038853418682988686871489963827000080098971762923" +
1967
"833614557257607521";
1968
private static final String RSA_1024_PRIV = "03682574144968491431483287" +
1969
"297021581096848810374110568017963075809477047466189822987258068867" +
1970
"704855380407747867998863645890602646601140183818953428006646987710" +
1971
"237008997971129772408397621801631622129297063463868593083106979716" +
1972
"204903524890556839550490384015324575598723478554854070823335021842" +
1973
"210112348400928769";
1974
private static final String RSA_2048_MOD = "243987087691547796017401146540"
1975
+ "9844666035826535295137885613771811531602666348704672255163984907599"
1976
+ "4298308997053582963763109207465354916871136820987101812436158377530"
1977
+ "6117270010853232249007544652859474372258057062943608962079402484091"
1978
+ "8121307687901225514249308620012025884376216406019656605767311580224"
1979
+ "4715304950770504195751384382230005665573033547124060755957932161045"
1980
+ "7288008201789401237690181537646952377591671113513382933711547044631"
1981
+ "6055957820531234310030119265612054594720774653570278810236807313332"
1982
+ "5293876225940483622056721445101719346295263740434720907474414905706"
1983
+ "086605825077661246082956613711071075569880930102141";
1984
private static final String RSA_2048_PRIV = "12265063405401593206575340300"
1985
+ "5824698296458954796982342251774894076489082263237675553422307220014"
1986
+ "4395010131540855227949365446755185799985229111139387016816011165826"
1987
+ "5498929552020323994756478872375078784799489891112924298115119573429"
1988
+ "3677627114115546751555523555375278381312502020990154549150867571006"
1989
+ "4470674155961982582802981649643127000520693025433874996570667724459"
1990
+ "3395670697152709457274026580106078581585077146782827694403672461289"
1991
+ "9143004401242754355097671446183871158504602884373174300123820136505"
1992
+ "6449932139773607305129273545117363975014750743804523418307647791195"
1993
+ "6408859873123458434820062206102268853256685162004893";
1994
private static final String EC_P256_X =
1995
"335863644451761614592446380116804721648611739647823420286081723541" +
1996
"6166183710";
1997
private static final String EC_P256_Y =
1998
"951559601159729477487064127150143688502130342917782252098602422796" +
1999
"95457910701";
2000
private static final String EC_P256_S =
2001
"425976209773168452211813225517384419928639977904006759709292218082" +
2002
"7440083936";
2003
private static final ECParameterSpec EC_P256_PARAMS = initECParams(
2004
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",
2005
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",
2006
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B",
2007
"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
2008
"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",
2009
"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551",
2010
1
2011
);
2012
private static final String EC_P384_X =
2013
"12144058647679082341340699736608428955270957565259459672517275506071643671835484144490620216582303669654008841724053";
2014
private static final String EC_P384_Y =
2015
"18287745972107701566600963632634101287058332546756092926848497481238534346489545826483592906634896557151987868614320";
2016
private static final String EC_P384_S =
2017
"10307785759830534742680442271492590599236624208247590184679565032330507874096079979152605984203102224450595283943382";
2018
private static final ECParameterSpec EC_P384_PARAMS = initECParams(
2019
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF",
2020
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC",
2021
"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF",
2022
"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7",
2023
"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F",
2024
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973",
2025
1
2026
);
2027
private static final String EC_P521_X =
2028
"4157918188927862838251799402582135611021257663417126086145819679867926857146776190737187582274664373117054717389603317411991660346043842712448912355335343997";
2029
private static final String EC_P521_Y =
2030
"4102838062751704796157456866854813794620023146924181568434486703918224542844053923233919899911519054998554969832861957437850996213216829205401947264294066288";
2031
private static final String EC_P521_S =
2032
"4857798533181496041050215963883119936300918353498701880968530610687256097257307590162398707429640390843595868713096292822034014722985178583665959048714417342";
2033
private static final ECParameterSpec EC_P521_PARAMS = initECParams(
2034
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
2035
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC",
2036
"0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00",
2037
"00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66",
2038
"011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650",
2039
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409",
2040
1
2041
);
2042
2043
private static ECParameterSpec initECParams(
2044
String sfield, String a, String b, String gx, String gy,
2045
String n, int h) {
2046
ECField field = new ECFieldFp(bigInt(sfield));
2047
EllipticCurve curve = new EllipticCurve(field,
2048
bigInt(a), bigInt(b));
2049
ECPoint g = new ECPoint(bigInt(gx), bigInt(gy));
2050
return new ECParameterSpec(curve, g, bigInt(n), h);
2051
}
2052
2053
private static BigInteger bigInt(String s) {
2054
return new BigInteger(s, 16);
2055
}
2056
private static PublicKey getPublicKey(String algo, int keysize)
2057
throws Exception {
2058
KeyFactory kf = KeyFactory.getInstance(algo);
2059
KeySpec kspec;
2060
if (algo.equalsIgnoreCase("DSA")) {
2061
if (keysize == 1024) {
2062
kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),
2063
new BigInteger(DSA_P),
2064
new BigInteger(DSA_Q),
2065
new BigInteger(DSA_G));
2066
} else if (keysize == 2048) {
2067
kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y),
2068
new BigInteger(DSA_2048_P),
2069
new BigInteger(DSA_2048_Q),
2070
new BigInteger(DSA_2048_G));
2071
} else throw new RuntimeException("Unsupported keysize:" + keysize);
2072
} else if (algo.equalsIgnoreCase("RSA")) {
2073
if (keysize == 512) {
2074
kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD),
2075
new BigInteger(RSA_PUB));
2076
} else if (keysize == 1024) {
2077
kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),
2078
new BigInteger(RSA_PUB));
2079
} else if (keysize == 2048) {
2080
kspec = new RSAPublicKeySpec(new BigInteger(RSA_2048_MOD),
2081
new BigInteger(RSA_PUB));
2082
} else throw new RuntimeException("Unsupported keysize:" + keysize);
2083
} else throw new RuntimeException("Unsupported key algorithm " + algo);
2084
return kf.generatePublic(kspec);
2085
}
2086
2087
private static PublicKey getECPublicKey(String curve) throws Exception {
2088
KeyFactory kf = KeyFactory.getInstance("EC");
2089
String x, y;
2090
ECParameterSpec params;
2091
switch (curve) {
2092
case "P256":
2093
x = EC_P256_X;
2094
y = EC_P256_Y;
2095
params = EC_P256_PARAMS;
2096
break;
2097
case "P384":
2098
x = EC_P384_X;
2099
y = EC_P384_Y;
2100
params = EC_P384_PARAMS;
2101
break;
2102
case "P521":
2103
x = EC_P521_X;
2104
y = EC_P521_Y;
2105
params = EC_P521_PARAMS;
2106
break;
2107
default:
2108
throw new Exception("Unsupported curve: " + curve);
2109
}
2110
KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x),
2111
new BigInteger(y)),
2112
params);
2113
return kf.generatePublic(kspec);
2114
}
2115
2116
private static PrivateKey getPrivateKey(String algo, int keysize)
2117
throws Exception {
2118
KeyFactory kf = KeyFactory.getInstance(algo);
2119
KeySpec kspec;
2120
if (algo.equalsIgnoreCase("DSA")) {
2121
if (keysize == 1024) {
2122
kspec = new DSAPrivateKeySpec
2123
(new BigInteger(DSA_X), new BigInteger(DSA_P),
2124
new BigInteger(DSA_Q), new BigInteger(DSA_G));
2125
} else if (keysize == 2048) {
2126
kspec = new DSAPrivateKeySpec
2127
(new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P),
2128
new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));
2129
} else throw new RuntimeException("Unsupported keysize:" + keysize);
2130
} else if (algo.equalsIgnoreCase("RSA")) {
2131
if (keysize == 512) {
2132
kspec = new RSAPrivateKeySpec
2133
(new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV));
2134
} else if (keysize == 1024) {
2135
kspec = new RSAPrivateKeySpec(new BigInteger(RSA_1024_MOD),
2136
new BigInteger(RSA_1024_PRIV));
2137
} else if (keysize == 2048) {
2138
kspec = new RSAPrivateKeySpec(new BigInteger(RSA_2048_MOD),
2139
new BigInteger(RSA_2048_PRIV));
2140
} else throw new RuntimeException("Unsupported key algorithm " + algo);
2141
} else throw new RuntimeException("Unsupported key algorithm " + algo);
2142
return kf.generatePrivate(kspec);
2143
}
2144
2145
private static PrivateKey getECPrivateKey(String curve) throws Exception {
2146
String s;
2147
ECParameterSpec params;
2148
switch (curve) {
2149
case "P256":
2150
s = EC_P256_S;
2151
params = EC_P256_PARAMS;
2152
break;
2153
case "P384":
2154
s = EC_P384_S;
2155
params = EC_P384_PARAMS;
2156
break;
2157
case "P521":
2158
s = EC_P521_S;
2159
params = EC_P521_PARAMS;
2160
break;
2161
default:
2162
throw new Exception("Unsupported curve: " + curve);
2163
}
2164
KeyFactory kf = KeyFactory.getInstance("EC");
2165
KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);
2166
return kf.generatePrivate(kspec);
2167
}
2168
2169
private static SecretKey getSecretKey(final byte[] secret) {
2170
return new SecretKey() {
2171
public String getFormat() { return "RAW"; }
2172
public byte[] getEncoded() { return secret; }
2173
public String getAlgorithm(){ return "SECRET"; }
2174
};
2175
}
2176
2177
/**
2178
* This URIDereferencer returns locally cached copies of http content to
2179
* avoid test failures due to network glitches, etc.
2180
*/
2181
private static class HttpURIDereferencer implements URIDereferencer {
2182
private URIDereferencer defaultUd;
2183
2184
HttpURIDereferencer() {
2185
defaultUd = XMLSignatureFactory.getInstance().getURIDereferencer();
2186
}
2187
2188
public Data dereference(final URIReference ref, XMLCryptoContext ctx)
2189
throws URIReferenceException {
2190
String uri = ref.getURI();
2191
if (uri.equals(STYLESHEET) || uri.equals(STYLESHEET_B64)) {
2192
try {
2193
FileInputStream fis = new FileInputStream(new File
2194
(DATA_DIR, uri.substring(uri.lastIndexOf('/'))));
2195
return new OctetStreamData(fis,ref.getURI(),ref.getType());
2196
} catch (Exception e) { throw new URIReferenceException(e); }
2197
} else if (uri.startsWith("certs/")) {
2198
try {
2199
FileInputStream fis = new FileInputStream(new File
2200
(DATA_DIR, uri));
2201
return new OctetStreamData(fis,ref.getURI(),ref.getType());
2202
} catch (Exception e) { throw new URIReferenceException(e); }
2203
}
2204
2205
// fallback on builtin deref
2206
return defaultUd.dereference(ref, ctx);
2207
}
2208
}
2209
2210
// local http server
2211
static class Http implements HttpHandler, AutoCloseable {
2212
2213
private final HttpServer server;
2214
2215
private Http(HttpServer server) {
2216
this.server = server;
2217
}
2218
2219
static Http startServer() throws IOException {
2220
HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
2221
return new Http(server);
2222
}
2223
2224
void start() {
2225
server.createContext("/", this);
2226
server.start();
2227
}
2228
2229
void stop() {
2230
server.stop(0);
2231
}
2232
2233
int getPort() {
2234
return server.getAddress().getPort();
2235
}
2236
2237
@Override
2238
public void handle(HttpExchange t) throws IOException {
2239
try {
2240
String type;
2241
String path = t.getRequestURI().getPath();
2242
if (path.startsWith("/")) {
2243
type = path.substring(1);
2244
} else {
2245
type = path;
2246
}
2247
2248
String contentTypeHeader = "";
2249
byte[] output = new byte[] {};
2250
int code = 200;
2251
Content testContentType = Content.valueOf(type);
2252
switch (testContentType) {
2253
case Base64:
2254
contentTypeHeader = "application/octet-stream";
2255
output = "VGVzdA==".getBytes();
2256
break;
2257
case Text:
2258
contentTypeHeader = "text/plain";
2259
output = "Text".getBytes();
2260
break;
2261
case Xml:
2262
contentTypeHeader = "application/xml";
2263
output = "<tag>test</tag>".getBytes();
2264
break;
2265
case NotExisitng:
2266
code = 404;
2267
break;
2268
default:
2269
throw new IOException("Unknown test content type");
2270
}
2271
2272
t.getResponseHeaders().set("Content-Type", contentTypeHeader);
2273
t.sendResponseHeaders(code, output.length);
2274
t.getResponseBody().write(output);
2275
} catch (IOException e) {
2276
System.out.println("Exception: " + e);
2277
t.sendResponseHeaders(500, 0);
2278
}
2279
t.close();
2280
}
2281
2282
@Override
2283
public void close() {
2284
stop();
2285
}
2286
}
2287
}
2288
2289