Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/javax/xml/crypto/dsig/GenerationTests.java
41152 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.setBaseURI(f.toURI().toString());
1458
dvc.setURIDereferencer(httpUd);
1459
1460
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1461
1462
if (sig.equals(sig2) == false) {
1463
throw new Exception
1464
("Unmarshalled signature is not equal to generated signature");
1465
}
1466
if (sig2.validate(dvc) == false) {
1467
throw new Exception("Validation of generated signature failed");
1468
}
1469
}
1470
1471
private static void test_create_signature_enveloping
1472
(DigestMethod dm, SignatureMethod sm, KeyInfo ki, Key signingKey,
1473
KeySelector ks, boolean b64, boolean secVal) throws Exception {
1474
1475
// create reference
1476
Reference ref;
1477
if (b64) {
1478
ref = fac.newReference("#object", dm, Collections.singletonList
1479
(fac.newTransform(Transform.BASE64,
1480
(TransformParameterSpec) null)), null, null);
1481
} else {
1482
ref = fac.newReference("#object", dm);
1483
}
1484
1485
// create SignedInfo
1486
SignedInfo si = fac.newSignedInfo(withoutComments, sm,
1487
Collections.singletonList(ref));
1488
1489
Document doc = db.newDocument();
1490
// create Objects
1491
String text = b64 ? "c29tZSB0ZXh0" : "some text";
1492
XMLObject obj = fac.newXMLObject(Collections.singletonList
1493
(new DOMStructure(doc.createTextNode(text))),
1494
"object", null, null);
1495
1496
// create XMLSignature
1497
XMLSignature sig = fac.newXMLSignature
1498
(si, ki, Collections.singletonList(obj), null, null);
1499
1500
DOMSignContext dsc = new DOMSignContext(signingKey, doc);
1501
1502
sig.sign(dsc);
1503
1504
// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1505
1506
DOMValidateContext dvc = new DOMValidateContext
1507
(ks, doc.getDocumentElement());
1508
dvc.setProperty("org.jcp.xml.dsig.secureValidation", secVal);
1509
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1510
1511
if (sig.equals(sig2) == false) {
1512
throw new Exception
1513
("Unmarshalled signature is not equal to generated signature");
1514
}
1515
if (sig2.validate(dvc) == false) {
1516
throw new Exception("Validation of generated signature failed");
1517
}
1518
}
1519
1520
static void test_create_exc_signature() throws Exception {
1521
System.out.println("* Generating exc_signature.xml");
1522
List<Reference> refs = new ArrayList<>(4);
1523
1524
// create reference 1
1525
refs.add(fac.newReference
1526
("#xpointer(id('to-be-signed'))", sha1,
1527
Collections.singletonList
1528
(fac.newTransform(CanonicalizationMethod.EXCLUSIVE,
1529
(TransformParameterSpec) null)),
1530
null, null));
1531
1532
// create reference 2
1533
List<String> prefixList = new ArrayList<>(2);
1534
prefixList.add("bar");
1535
prefixList.add("#default");
1536
ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);
1537
refs.add(fac.newReference
1538
("#xpointer(id('to-be-signed'))", sha1,
1539
Collections.singletonList
1540
(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)),
1541
null, null));
1542
1543
// create reference 3
1544
refs.add(fac.newReference
1545
("#xpointer(id('to-be-signed'))", sha1,
1546
Collections.singletonList(fac.newTransform
1547
(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
1548
(TransformParameterSpec) null)),
1549
null, null));
1550
1551
// create reference 4
1552
prefixList = new ArrayList<>(2);
1553
prefixList.add("bar");
1554
prefixList.add("#default");
1555
params = new ExcC14NParameterSpec(prefixList);
1556
refs.add(fac.newReference
1557
("#xpointer(id('to-be-signed'))", sha1,
1558
Collections.singletonList(fac.newTransform
1559
(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)),
1560
null, null));
1561
1562
// create SignedInfo
1563
SignedInfo si = fac.newSignedInfo(
1564
fac.newCanonicalizationMethod
1565
(CanonicalizationMethod.EXCLUSIVE,
1566
(C14NMethodParameterSpec) null),
1567
dsaSha1, refs);
1568
1569
// create KeyInfo
1570
List<XMLStructure> kits = new ArrayList<>(2);
1571
kits.add(kifac.newKeyValue(validatingKey));
1572
KeyInfo ki = kifac.newKeyInfo(kits);
1573
1574
// create Objects
1575
Document doc = db.newDocument();
1576
Element baz = doc.createElementNS("urn:bar", "bar:Baz");
1577
Comment com = doc.createComment(" comment ");
1578
baz.appendChild(com);
1579
XMLObject obj = fac.newXMLObject(Collections.singletonList
1580
(new DOMStructure(baz)), "to-be-signed", null, null);
1581
1582
// create XMLSignature
1583
XMLSignature sig = fac.newXMLSignature
1584
(si, ki, Collections.singletonList(obj), null, null);
1585
1586
Element foo = doc.createElementNS("urn:foo", "Foo");
1587
foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");
1588
foo.setAttributeNS
1589
("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");
1590
doc.appendChild(foo);
1591
1592
DOMSignContext dsc = new DOMSignContext(signingKey, foo);
1593
dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");
1594
1595
sig.sign(dsc);
1596
1597
// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1598
1599
DOMValidateContext dvc = new DOMValidateContext
1600
(new KeySelectors.KeyValueKeySelector(), foo.getLastChild());
1601
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1602
1603
if (sig.equals(sig2) == false) {
1604
throw new Exception
1605
("Unmarshalled signature is not equal to generated signature");
1606
}
1607
if (sig2.validate(dvc) == false) {
1608
throw new Exception("Validation of generated signature failed");
1609
}
1610
System.out.println();
1611
}
1612
1613
static void test_create_sign_spec() throws Exception {
1614
System.out.println("* Generating sign-spec.xml");
1615
List<Reference> refs = new ArrayList<>(2);
1616
1617
// create reference 1
1618
List<XPathType> types = new ArrayList<>(3);
1619
types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT));
1620
types.add(new XPathType(" //NotToBeSigned ",
1621
XPathType.Filter.SUBTRACT));
1622
types.add(new XPathType(" //ReallyToBeSigned ",
1623
XPathType.Filter.UNION));
1624
XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);
1625
refs.add(fac.newReference("", sha1,
1626
Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)),
1627
null, null));
1628
1629
// create reference 2
1630
List<Transform> trans2 = new ArrayList<>(2);
1631
trans2.add(fac.newTransform(Transform.ENVELOPED,
1632
(TransformParameterSpec) null));
1633
XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec
1634
(Collections.singletonList
1635
(new XPathType(" / ", XPathType.Filter.UNION)));
1636
trans2.add(fac.newTransform(Transform.XPATH2, xp2));
1637
refs.add(fac.newReference("#signature-value", sha1, trans2, null, null));
1638
1639
// create SignedInfo
1640
SignedInfo si = fac.newSignedInfo(
1641
fac.newCanonicalizationMethod
1642
(CanonicalizationMethod.INCLUSIVE,
1643
(C14NMethodParameterSpec) null),
1644
dsaSha1, refs);
1645
1646
// create KeyInfo
1647
List<XMLStructure> kits = new ArrayList<>(2);
1648
kits.add(kifac.newKeyValue(validatingKey));
1649
List<Object> xds = new ArrayList<>(2);
1650
xds.add("CN=User");
1651
xds.add(signingCert);
1652
kits.add(kifac.newX509Data(xds));
1653
KeyInfo ki = kifac.newKeyInfo(kits);
1654
1655
// create XMLSignature
1656
XMLSignature sig = fac.newXMLSignature
1657
(si, ki, null, null, "signature-value");
1658
1659
Document doc = db.newDocument();
1660
Element tbs1 = doc.createElementNS(null, "ToBeSigned");
1661
Comment tbs1Com = doc.createComment(" comment ");
1662
Element tbs1Data = doc.createElementNS(null, "Data");
1663
Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned");
1664
Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned");
1665
Comment tbs1rtbsCom = doc.createComment(" comment ");
1666
Element tbs1rtbsData = doc.createElementNS(null, "Data");
1667
tbs1rtbs.appendChild(tbs1rtbsCom);
1668
tbs1rtbs.appendChild(tbs1rtbsData);
1669
tbs1ntbs.appendChild(tbs1rtbs);
1670
tbs1.appendChild(tbs1Com);
1671
tbs1.appendChild(tbs1Data);
1672
tbs1.appendChild(tbs1ntbs);
1673
1674
Element tbs2 = doc.createElementNS(null, "ToBeSigned");
1675
Element tbs2Data = doc.createElementNS(null, "Data");
1676
Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned");
1677
Element tbs2ntbsData = doc.createElementNS(null, "Data");
1678
tbs2ntbs.appendChild(tbs2ntbsData);
1679
tbs2.appendChild(tbs2Data);
1680
tbs2.appendChild(tbs2ntbs);
1681
1682
Element document = doc.createElementNS(null, "Document");
1683
document.appendChild(tbs1);
1684
document.appendChild(tbs2);
1685
doc.appendChild(document);
1686
1687
DOMSignContext dsc = new DOMSignContext(signingKey, document);
1688
1689
sig.sign(dsc);
1690
1691
// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
1692
1693
DOMValidateContext dvc = new DOMValidateContext
1694
(new KeySelectors.KeyValueKeySelector(), document.getLastChild());
1695
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
1696
1697
if (sig.equals(sig2) == false) {
1698
throw new Exception
1699
("Unmarshalled signature is not equal to generated signature");
1700
}
1701
if (sig2.validate(dvc) == false) {
1702
throw new Exception("Validation of generated signature failed");
1703
}
1704
System.out.println();
1705
}
1706
1707
// Only print if there is an error.
1708
static void test_create_detached_signature(
1709
String canonicalizationMethod, String signatureMethod,
1710
String digestMethod, String transform, KeyInfoType keyInfo,
1711
Content contentType, int port, boolean expectedFailure,
1712
Class expectedException) {
1713
1714
String title = "\nTest detached signature:"
1715
+ "\n Canonicalization method: " + canonicalizationMethod
1716
+ "\n Signature method: " + signatureMethod
1717
+ "\n Transform: " + transform
1718
+ "\n Digest method: " + digestMethod
1719
+ "\n KeyInfoType: " + keyInfo
1720
+ "\n Content type: " + contentType
1721
+ "\n Expected failure: " + (expectedFailure ? "yes" : "no")
1722
+ "\n Expected exception: " + (expectedException == null ?
1723
"no" : expectedException.getName());
1724
1725
try {
1726
boolean success = test_create_detached_signature0(
1727
canonicalizationMethod,
1728
signatureMethod,
1729
digestMethod,
1730
transform,
1731
keyInfo,
1732
contentType,
1733
port);
1734
1735
if (success && expectedFailure) {
1736
System.out.println(title);
1737
System.out.println("Signature validation unexpectedly passed");
1738
result = false;
1739
} else if (!success && !expectedFailure) {
1740
System.out.println(title);
1741
System.out.println("Signature validation unexpectedly failed");
1742
result = false;
1743
} else if (expectedException != null) {
1744
System.out.println(title);
1745
System.out.println("Expected " + expectedException
1746
+ " not thrown");
1747
result = false;
1748
}
1749
} catch (Exception e) {
1750
if (expectedException == null
1751
|| !e.getClass().isAssignableFrom(expectedException)) {
1752
System.out.println(title);
1753
System.out.println("Unexpected exception: " + e);
1754
e.printStackTrace(System.out);
1755
result = false;
1756
}
1757
}
1758
}
1759
1760
// Print out as little as possible. This method will be called many times.
1761
static boolean test_create_detached_signature0(String canonicalizationMethod,
1762
String signatureMethod, String digestMethod, String transform,
1763
KeyInfoType keyInfo, Content contentType, int port)
1764
throws Exception {
1765
1766
System.out.print("-S");
1767
System.out.flush();
1768
1769
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1770
dbf.setNamespaceAware(true);
1771
dbf.setValidating(false);
1772
1773
// Create SignedInfo
1774
DigestMethod dm = fac.newDigestMethod(digestMethod, null);
1775
1776
List transformList = null;
1777
if (transform != null) {
1778
TransformParameterSpec params = null;
1779
switch (transform) {
1780
case Transform.XPATH:
1781
params = new XPathFilterParameterSpec("//.");
1782
break;
1783
case Transform.XPATH2:
1784
params = new XPathFilter2ParameterSpec(
1785
Collections.singletonList(new XPathType("//.",
1786
XPathType.Filter.INTERSECT)));
1787
break;
1788
case Transform.XSLT:
1789
Element element = dbf.newDocumentBuilder()
1790
.parse(new ByteArrayInputStream(xslt.getBytes()))
1791
.getDocumentElement();
1792
DOMStructure stylesheet = new DOMStructure(element);
1793
params = new XSLTTransformParameterSpec(stylesheet);
1794
break;
1795
}
1796
transformList = Collections.singletonList(fac.newTransform(
1797
transform, params));
1798
}
1799
1800
String url = String.format("http://localhost:%d/%s", port, contentType);
1801
List refs = Collections.singletonList(fac.newReference(url, dm,
1802
transformList, null, null));
1803
1804
CanonicalizationMethod cm = fac.newCanonicalizationMethod(
1805
canonicalizationMethod, (C14NMethodParameterSpec) null);
1806
1807
SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
1808
1809
Key[] pair = getCachedKeys(signatureMethod);
1810
Key signingKey = pair[0];
1811
Key validationKey = pair[1];
1812
1813
SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
1814
1815
// Create KeyInfo
1816
KeyInfoFactory kif = fac.getKeyInfoFactory();
1817
List list = null;
1818
if (keyInfo == KeyInfoType.KeyValue) {
1819
if (validationKey instanceof PublicKey) {
1820
KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
1821
list = Collections.singletonList(kv);
1822
}
1823
} else if (keyInfo == KeyInfoType.x509data) {
1824
list = Collections.singletonList(
1825
kif.newX509Data(Collections.singletonList("cn=Test")));
1826
} else if (keyInfo == KeyInfoType.KeyName) {
1827
list = Collections.singletonList(kif.newKeyName("Test"));
1828
} else {
1829
throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
1830
}
1831
KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
1832
1833
// Create an empty doc for detached signature
1834
Document doc = dbf.newDocumentBuilder().newDocument();
1835
DOMSignContext xsc = new DOMSignContext(signingKey, doc);
1836
1837
// Generate signature
1838
XMLSignature signature = fac.newXMLSignature(si, ki);
1839
signature.sign(xsc);
1840
1841
// Save signature
1842
String signatureString;
1843
try (StringWriter writer = new StringWriter()) {
1844
TransformerFactory tf = TransformerFactory.newInstance();
1845
Transformer trans = tf.newTransformer();
1846
Node parent = xsc.getParent();
1847
trans.transform(new DOMSource(parent), new StreamResult(writer));
1848
signatureString = writer.toString();
1849
}
1850
1851
System.out.print("V");
1852
System.out.flush();
1853
try (ByteArrayInputStream bis = new ByteArrayInputStream(
1854
signatureString.getBytes())) {
1855
doc = dbf.newDocumentBuilder().parse(bis);
1856
}
1857
1858
NodeList nodeLst = doc.getElementsByTagName("Signature");
1859
Node node = nodeLst.item(0);
1860
if (node == null) {
1861
throw new RuntimeException("Couldn't find Signature element");
1862
}
1863
if (!(node instanceof Element)) {
1864
throw new RuntimeException("Unexpected node type");
1865
}
1866
Element sig = (Element) node;
1867
1868
// Validate signature
1869
DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
1870
vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
1871
signature = fac.unmarshalXMLSignature(vc);
1872
1873
boolean success = signature.validate(vc);
1874
if (!success) {
1875
System.out.print("x");
1876
System.out.flush();
1877
return false;
1878
}
1879
1880
success = signature.getSignatureValue().validate(vc);
1881
if (!success) {
1882
System.out.print("X");
1883
System.out.flush();
1884
return false;
1885
}
1886
1887
return true;
1888
}
1889
1890
private static Key[] getCachedKeys(String signatureMethod) {
1891
return cachedKeys.computeIfAbsent(signatureMethod, sm -> {
1892
try {
1893
System.out.print("<create keys for " + sm + ">");
1894
System.out.flush();
1895
if (sm.contains("#hmac-")) {
1896
// http://...#hmac-sha1 -> hmac-sha1 -> hmacsha1
1897
String algName = sm
1898
.substring(sm.indexOf('#') + 1)
1899
.replace("-", "");
1900
KeyGenerator kg = KeyGenerator.getInstance(algName);
1901
Key signingKey = kg.generateKey();
1902
return new Key[] { signingKey, signingKey};
1903
} else {
1904
KeyPairGenerator kpg;
1905
if (sm.contains("#rsa-")
1906
|| sm.contains("-rsa-MGF1")) {
1907
kpg = KeyPairGenerator.getInstance("RSA");
1908
kpg.initialize(
1909
sm.contains("#sha512-rsa-MGF1") ? 2048 : 1024);
1910
} else if (sm.contains("#dsa-")) {
1911
kpg = KeyPairGenerator.getInstance("DSA");
1912
kpg.initialize(1024);
1913
} else if (sm.contains("#ecdsa-")) {
1914
kpg = KeyPairGenerator.getInstance("EC");
1915
kpg.initialize(256);
1916
} else {
1917
throw new RuntimeException("Unsupported signature algorithm");
1918
}
1919
KeyPair kp = kpg.generateKeyPair();
1920
return new Key[] { kp.getPrivate(), kp.getPublic()};
1921
}
1922
} catch (NoSuchAlgorithmException e) {
1923
throw new AssertionError("Should not happen", e);
1924
}
1925
});
1926
}
1927
1928
private static final String DSA_Y =
1929
"070662842167565771936588335128634396171789331656318483584455493822" +
1930
"400811200853331373030669235424928346190274044631949560438023934623" +
1931
"71310375123430985057160";
1932
private static final String DSA_P =
1933
"013232376895198612407547930718267435757728527029623408872245156039" +
1934
"757713029036368719146452186041204237350521785240337048752071462798" +
1935
"273003935646236777459223";
1936
private static final String DSA_Q =
1937
"0857393771208094202104259627990318636601332086981";
1938
private static final String DSA_G =
1939
"054216440574364751416096484883257051280474283943804743768346673007" +
1940
"661082626139005426812890807137245973106730741193551360857959820973" +
1941
"90670890367185141189796";
1942
private static final String DSA_X =
1943
"0527140396812450214498055937934275626078768840117";
1944
private static final String DSA_2048_Y =
1945
"15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928";
1946
private static final String DSA_2048_P =
1947
"18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359";
1948
private static final String DSA_2048_Q =
1949
"19689526866605154788513693571065914024068069442724893395618704484701";
1950
private static final String DSA_2048_G =
1951
"2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430";
1952
private static final String DSA_2048_X =
1953
"14562787764977288900757387442281559936279834964901963465277698843172";
1954
private static final String RSA_MOD =
1955
"010800185049102889923150759252557522305032794699952150943573164381" +
1956
"936603255999071981574575044810461362008102247767482738822150129277" +
1957
"490998033971789476107463";
1958
private static final String RSA_PRIV =
1959
"016116973584421969795445996229612671947635798429212816611707210835" +
1960
"915586591340598683996088487065438751488342251960069575392056288063" +
1961
"6800379454345804879553";
1962
private static final String RSA_PUB = "065537";
1963
private static final String RSA_1024_MOD = "098871307553789439961130765" +
1964
"909423744508062468450669519128736624058048856940468016843888594585" +
1965
"322862378444314635412341974900625010364163960238734457710620107530" +
1966
"573945081856371709138380902553309075505688814637544923038853658690" +
1967
"857672483016239697038853418682988686871489963827000080098971762923" +
1968
"833614557257607521";
1969
private static final String RSA_1024_PRIV = "03682574144968491431483287" +
1970
"297021581096848810374110568017963075809477047466189822987258068867" +
1971
"704855380407747867998863645890602646601140183818953428006646987710" +
1972
"237008997971129772408397621801631622129297063463868593083106979716" +
1973
"204903524890556839550490384015324575598723478554854070823335021842" +
1974
"210112348400928769";
1975
private static final String RSA_2048_MOD = "243987087691547796017401146540"
1976
+ "9844666035826535295137885613771811531602666348704672255163984907599"
1977
+ "4298308997053582963763109207465354916871136820987101812436158377530"
1978
+ "6117270010853232249007544652859474372258057062943608962079402484091"
1979
+ "8121307687901225514249308620012025884376216406019656605767311580224"
1980
+ "4715304950770504195751384382230005665573033547124060755957932161045"
1981
+ "7288008201789401237690181537646952377591671113513382933711547044631"
1982
+ "6055957820531234310030119265612054594720774653570278810236807313332"
1983
+ "5293876225940483622056721445101719346295263740434720907474414905706"
1984
+ "086605825077661246082956613711071075569880930102141";
1985
private static final String RSA_2048_PRIV = "12265063405401593206575340300"
1986
+ "5824698296458954796982342251774894076489082263237675553422307220014"
1987
+ "4395010131540855227949365446755185799985229111139387016816011165826"
1988
+ "5498929552020323994756478872375078784799489891112924298115119573429"
1989
+ "3677627114115546751555523555375278381312502020990154549150867571006"
1990
+ "4470674155961982582802981649643127000520693025433874996570667724459"
1991
+ "3395670697152709457274026580106078581585077146782827694403672461289"
1992
+ "9143004401242754355097671446183871158504602884373174300123820136505"
1993
+ "6449932139773607305129273545117363975014750743804523418307647791195"
1994
+ "6408859873123458434820062206102268853256685162004893";
1995
private static final String EC_P256_X =
1996
"335863644451761614592446380116804721648611739647823420286081723541" +
1997
"6166183710";
1998
private static final String EC_P256_Y =
1999
"951559601159729477487064127150143688502130342917782252098602422796" +
2000
"95457910701";
2001
private static final String EC_P256_S =
2002
"425976209773168452211813225517384419928639977904006759709292218082" +
2003
"7440083936";
2004
private static final ECParameterSpec EC_P256_PARAMS = initECParams(
2005
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",
2006
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",
2007
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B",
2008
"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
2009
"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",
2010
"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551",
2011
1
2012
);
2013
private static final String EC_P384_X =
2014
"12144058647679082341340699736608428955270957565259459672517275506071643671835484144490620216582303669654008841724053";
2015
private static final String EC_P384_Y =
2016
"18287745972107701566600963632634101287058332546756092926848497481238534346489545826483592906634896557151987868614320";
2017
private static final String EC_P384_S =
2018
"10307785759830534742680442271492590599236624208247590184679565032330507874096079979152605984203102224450595283943382";
2019
private static final ECParameterSpec EC_P384_PARAMS = initECParams(
2020
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF",
2021
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC",
2022
"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF",
2023
"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7",
2024
"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F",
2025
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973",
2026
1
2027
);
2028
private static final String EC_P521_X =
2029
"4157918188927862838251799402582135611021257663417126086145819679867926857146776190737187582274664373117054717389603317411991660346043842712448912355335343997";
2030
private static final String EC_P521_Y =
2031
"4102838062751704796157456866854813794620023146924181568434486703918224542844053923233919899911519054998554969832861957437850996213216829205401947264294066288";
2032
private static final String EC_P521_S =
2033
"4857798533181496041050215963883119936300918353498701880968530610687256097257307590162398707429640390843595868713096292822034014722985178583665959048714417342";
2034
private static final ECParameterSpec EC_P521_PARAMS = initECParams(
2035
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
2036
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC",
2037
"0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00",
2038
"00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66",
2039
"011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650",
2040
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409",
2041
1
2042
);
2043
2044
private static ECParameterSpec initECParams(
2045
String sfield, String a, String b, String gx, String gy,
2046
String n, int h) {
2047
ECField field = new ECFieldFp(bigInt(sfield));
2048
EllipticCurve curve = new EllipticCurve(field,
2049
bigInt(a), bigInt(b));
2050
ECPoint g = new ECPoint(bigInt(gx), bigInt(gy));
2051
return new ECParameterSpec(curve, g, bigInt(n), h);
2052
}
2053
2054
private static BigInteger bigInt(String s) {
2055
return new BigInteger(s, 16);
2056
}
2057
private static PublicKey getPublicKey(String algo, int keysize)
2058
throws Exception {
2059
KeyFactory kf = KeyFactory.getInstance(algo);
2060
KeySpec kspec;
2061
if (algo.equalsIgnoreCase("DSA")) {
2062
if (keysize == 1024) {
2063
kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),
2064
new BigInteger(DSA_P),
2065
new BigInteger(DSA_Q),
2066
new BigInteger(DSA_G));
2067
} else if (keysize == 2048) {
2068
kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y),
2069
new BigInteger(DSA_2048_P),
2070
new BigInteger(DSA_2048_Q),
2071
new BigInteger(DSA_2048_G));
2072
} else throw new RuntimeException("Unsupported keysize:" + keysize);
2073
} else if (algo.equalsIgnoreCase("RSA")) {
2074
if (keysize == 512) {
2075
kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD),
2076
new BigInteger(RSA_PUB));
2077
} else if (keysize == 1024) {
2078
kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),
2079
new BigInteger(RSA_PUB));
2080
} else if (keysize == 2048) {
2081
kspec = new RSAPublicKeySpec(new BigInteger(RSA_2048_MOD),
2082
new BigInteger(RSA_PUB));
2083
} else throw new RuntimeException("Unsupported keysize:" + keysize);
2084
} else throw new RuntimeException("Unsupported key algorithm " + algo);
2085
return kf.generatePublic(kspec);
2086
}
2087
2088
private static PublicKey getECPublicKey(String curve) throws Exception {
2089
KeyFactory kf = KeyFactory.getInstance("EC");
2090
String x, y;
2091
ECParameterSpec params;
2092
switch (curve) {
2093
case "P256":
2094
x = EC_P256_X;
2095
y = EC_P256_Y;
2096
params = EC_P256_PARAMS;
2097
break;
2098
case "P384":
2099
x = EC_P384_X;
2100
y = EC_P384_Y;
2101
params = EC_P384_PARAMS;
2102
break;
2103
case "P521":
2104
x = EC_P521_X;
2105
y = EC_P521_Y;
2106
params = EC_P521_PARAMS;
2107
break;
2108
default:
2109
throw new Exception("Unsupported curve: " + curve);
2110
}
2111
KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x),
2112
new BigInteger(y)),
2113
params);
2114
return kf.generatePublic(kspec);
2115
}
2116
2117
private static PrivateKey getPrivateKey(String algo, int keysize)
2118
throws Exception {
2119
KeyFactory kf = KeyFactory.getInstance(algo);
2120
KeySpec kspec;
2121
if (algo.equalsIgnoreCase("DSA")) {
2122
if (keysize == 1024) {
2123
kspec = new DSAPrivateKeySpec
2124
(new BigInteger(DSA_X), new BigInteger(DSA_P),
2125
new BigInteger(DSA_Q), new BigInteger(DSA_G));
2126
} else if (keysize == 2048) {
2127
kspec = new DSAPrivateKeySpec
2128
(new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P),
2129
new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));
2130
} else throw new RuntimeException("Unsupported keysize:" + keysize);
2131
} else if (algo.equalsIgnoreCase("RSA")) {
2132
if (keysize == 512) {
2133
kspec = new RSAPrivateKeySpec
2134
(new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV));
2135
} else if (keysize == 1024) {
2136
kspec = new RSAPrivateKeySpec(new BigInteger(RSA_1024_MOD),
2137
new BigInteger(RSA_1024_PRIV));
2138
} else if (keysize == 2048) {
2139
kspec = new RSAPrivateKeySpec(new BigInteger(RSA_2048_MOD),
2140
new BigInteger(RSA_2048_PRIV));
2141
} else throw new RuntimeException("Unsupported key algorithm " + algo);
2142
} else throw new RuntimeException("Unsupported key algorithm " + algo);
2143
return kf.generatePrivate(kspec);
2144
}
2145
2146
private static PrivateKey getECPrivateKey(String curve) throws Exception {
2147
String s;
2148
ECParameterSpec params;
2149
switch (curve) {
2150
case "P256":
2151
s = EC_P256_S;
2152
params = EC_P256_PARAMS;
2153
break;
2154
case "P384":
2155
s = EC_P384_S;
2156
params = EC_P384_PARAMS;
2157
break;
2158
case "P521":
2159
s = EC_P521_S;
2160
params = EC_P521_PARAMS;
2161
break;
2162
default:
2163
throw new Exception("Unsupported curve: " + curve);
2164
}
2165
KeyFactory kf = KeyFactory.getInstance("EC");
2166
KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);
2167
return kf.generatePrivate(kspec);
2168
}
2169
2170
private static SecretKey getSecretKey(final byte[] secret) {
2171
return new SecretKey() {
2172
public String getFormat() { return "RAW"; }
2173
public byte[] getEncoded() { return secret; }
2174
public String getAlgorithm(){ return "SECRET"; }
2175
};
2176
}
2177
2178
/**
2179
* This URIDereferencer returns locally cached copies of http content to
2180
* avoid test failures due to network glitches, etc.
2181
*/
2182
private static class HttpURIDereferencer implements URIDereferencer {
2183
private URIDereferencer defaultUd;
2184
2185
HttpURIDereferencer() {
2186
defaultUd = XMLSignatureFactory.getInstance().getURIDereferencer();
2187
}
2188
2189
public Data dereference(final URIReference ref, XMLCryptoContext ctx)
2190
throws URIReferenceException {
2191
String uri = ref.getURI();
2192
if (uri.equals(STYLESHEET) || uri.equals(STYLESHEET_B64)) {
2193
try {
2194
FileInputStream fis = new FileInputStream(new File
2195
(DATA_DIR, uri.substring(uri.lastIndexOf('/'))));
2196
return new OctetStreamData(fis,ref.getURI(),ref.getType());
2197
} catch (Exception e) { throw new URIReferenceException(e); }
2198
}
2199
2200
// fallback on builtin deref
2201
return defaultUd.dereference(ref, ctx);
2202
}
2203
}
2204
2205
// local http server
2206
static class Http implements HttpHandler, AutoCloseable {
2207
2208
private final HttpServer server;
2209
2210
private Http(HttpServer server) {
2211
this.server = server;
2212
}
2213
2214
static Http startServer() throws IOException {
2215
HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
2216
return new Http(server);
2217
}
2218
2219
void start() {
2220
server.createContext("/", this);
2221
server.start();
2222
}
2223
2224
void stop() {
2225
server.stop(0);
2226
}
2227
2228
int getPort() {
2229
return server.getAddress().getPort();
2230
}
2231
2232
@Override
2233
public void handle(HttpExchange t) throws IOException {
2234
try {
2235
String type;
2236
String path = t.getRequestURI().getPath();
2237
if (path.startsWith("/")) {
2238
type = path.substring(1);
2239
} else {
2240
type = path;
2241
}
2242
2243
String contentTypeHeader = "";
2244
byte[] output = new byte[] {};
2245
int code = 200;
2246
Content testContentType = Content.valueOf(type);
2247
switch (testContentType) {
2248
case Base64:
2249
contentTypeHeader = "application/octet-stream";
2250
output = "VGVzdA==".getBytes();
2251
break;
2252
case Text:
2253
contentTypeHeader = "text/plain";
2254
output = "Text".getBytes();
2255
break;
2256
case Xml:
2257
contentTypeHeader = "application/xml";
2258
output = "<tag>test</tag>".getBytes();
2259
break;
2260
case NotExisitng:
2261
code = 404;
2262
break;
2263
default:
2264
throw new IOException("Unknown test content type");
2265
}
2266
2267
t.getResponseHeaders().set("Content-Type", contentTypeHeader);
2268
t.sendResponseHeaders(code, output.length);
2269
t.getResponseBody().write(output);
2270
} catch (IOException e) {
2271
System.out.println("Exception: " + e);
2272
t.sendResponseHeaders(500, 0);
2273
}
2274
t.close();
2275
}
2276
2277
@Override
2278
public void close() {
2279
stop();
2280
}
2281
}
2282
}
2283
2284