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