1 /* 2 * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /** 25 * @test 26 * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349 8046949 27 * 8046724 8079693 28 * @summary Basic unit tests for generating XML Signatures with JSR 105 29 * @modules java.base/sun.security.util 30 * java.base/sun.security.x509 31 * java.xml.crypto/org.jcp.xml.dsig.internal.dom 32 * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java 33 * X509KeySelector.java GenerationTests.java 34 * @run main/othervm GenerationTests 35 * @author Sean Mullan 36 */ 37 38 import java.io.*; 39 import java.math.BigInteger; 40 import java.security.Key; 41 import java.security.KeyFactory; 42 import java.security.KeyStore; 43 import java.security.PrivateKey; 44 import java.security.PublicKey; 45 import java.security.cert.Certificate; 46 import java.security.cert.CertificateFactory; 47 import java.security.cert.X509Certificate; 48 import java.security.cert.X509CRL; 49 import java.security.spec.KeySpec; 50 import java.security.spec.DSAPrivateKeySpec; 51 import java.security.spec.DSAPublicKeySpec; 52 import java.security.spec.ECField; 53 import java.security.spec.ECFieldFp; 54 import java.security.spec.ECParameterSpec; 55 import java.security.spec.ECPoint; 56 import java.security.spec.ECPrivateKeySpec; 57 import java.security.spec.ECPublicKeySpec; 58 import java.security.spec.EllipticCurve; 59 import java.security.spec.RSAPrivateKeySpec; 60 import java.security.spec.RSAPublicKeySpec; 61 import java.util.*; 62 import javax.crypto.SecretKey; 63 import javax.xml.XMLConstants; 64 import javax.xml.parsers.*; 65 import org.w3c.dom.*; 66 import javax.xml.crypto.Data; 67 import javax.xml.crypto.KeySelector; 68 import javax.xml.crypto.OctetStreamData; 69 import javax.xml.crypto.URIDereferencer; 70 import javax.xml.crypto.URIReference; 71 import javax.xml.crypto.URIReferenceException; 72 import javax.xml.crypto.XMLCryptoContext; 73 import javax.xml.crypto.XMLStructure; 74 import javax.xml.crypto.dsig.*; 75 import javax.xml.crypto.dom.*; 76 import javax.xml.crypto.dsig.dom.DOMSignContext; 77 import javax.xml.crypto.dsig.dom.DOMValidateContext; 78 import javax.xml.crypto.dsig.keyinfo.*; 79 import javax.xml.crypto.dsig.spec.*; 80 import javax.xml.transform.*; 81 import javax.xml.transform.dom.DOMSource; 82 import javax.xml.transform.stream.StreamResult; 83 84 /** 85 * Test that recreates merlin-xmldsig-twenty-three test vectors but with 86 * different keys and X.509 data. 87 */ 88 public class GenerationTests { 89 90 private static XMLSignatureFactory fac; 91 private static KeyInfoFactory kifac; 92 private static DocumentBuilder db; 93 private static CanonicalizationMethod withoutComments; 94 private static SignatureMethod dsaSha1, dsaSha256, rsaSha1, 95 rsaSha256, rsaSha384, rsaSha512, 96 ecdsaSha1; 97 private static DigestMethod sha1, sha256, sha384, sha512; 98 private static KeyInfo dsa1024, dsa2048, rsa, rsa1024, 99 p256ki, p384ki, p521ki; 100 private static KeySelector kvks = new KeySelectors.KeyValueKeySelector(); 101 private static KeySelector sks; 102 private static Key signingKey; 103 private static PublicKey validatingKey; 104 private static Certificate signingCert; 105 private static KeyStore ks; 106 private final static String DIR = System.getProperty("test.src", "."); 107 // private final static String DIR = "."; 108 private final static String DATA_DIR = 109 DIR + System.getProperty("file.separator") + "data"; 110 private final static String KEYSTORE = 111 DATA_DIR + System.getProperty("file.separator") + "certs" + 112 System.getProperty("file.separator") + "test.jks"; 113 private final static String CRL = 114 DATA_DIR + System.getProperty("file.separator") + "certs" + 115 System.getProperty("file.separator") + "crl"; 116 private final static String ENVELOPE = 117 DATA_DIR + System.getProperty("file.separator") + "envelope.xml"; 118 private static URIDereferencer httpUd = null; 119 private final static String STYLESHEET = 120 "http://www.w3.org/TR/xml-stylesheet"; 121 private final static String STYLESHEET_B64 = 122 "http://www.w3.org/Signature/2002/04/xml-stylesheet.b64"; 123 private final static String DSA_SHA256 = 124 "http://www.w3.org/2009/xmldsig11#dsa-sha256"; 125 126 public static void main(String args[]) throws Exception { 127 setup(); 128 test_create_signature_enveloped_dsa(1024); 129 test_create_signature_enveloped_dsa(2048); 130 test_create_signature_enveloping_b64_dsa(); 131 test_create_signature_enveloping_dsa(); 132 test_create_signature_enveloping_hmac_sha1_40(); 133 test_create_signature_enveloping_hmac_sha256(); 134 test_create_signature_enveloping_hmac_sha384(); 135 test_create_signature_enveloping_hmac_sha512(); 136 test_create_signature_enveloping_rsa(); 137 test_create_signature_enveloping_p256_sha1(); 138 test_create_signature_enveloping_p384_sha1(); 139 test_create_signature_enveloping_p521_sha1(); 140 test_create_signature_external_b64_dsa(); 141 test_create_signature_external_dsa(); 142 test_create_signature_keyname(); 143 test_create_signature_retrievalmethod_rawx509crt(); 144 test_create_signature_x509_crt_crl(); 145 test_create_signature_x509_crt(); 146 test_create_signature_x509_is(); 147 test_create_signature_x509_ski(); 148 test_create_signature_x509_sn(); 149 test_create_signature(); 150 test_create_exc_signature(); 151 test_create_sign_spec(); 152 test_create_signature_enveloping_sha256_dsa(); 153 test_create_signature_enveloping_sha384_rsa_sha256(); 154 test_create_signature_enveloping_sha512_rsa_sha384(); 155 test_create_signature_enveloping_sha512_rsa_sha512(); 156 test_create_signature_reference_dependency(); 157 test_create_signature_with_attr_in_no_namespace(); 158 test_create_signature_with_empty_id(); 159 } 160 161 private static void setup() throws Exception { 162 fac = XMLSignatureFactory.getInstance(); 163 kifac = fac.getKeyInfoFactory(); 164 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 165 dbf.setNamespaceAware(true); 166 db = dbf.newDocumentBuilder(); 167 168 // get key & self-signed certificate from keystore 169 FileInputStream fis = new FileInputStream(KEYSTORE); 170 ks = KeyStore.getInstance("JKS"); 171 ks.load(fis, "changeit".toCharArray()); 172 signingKey = ks.getKey("user", "changeit".toCharArray()); 173 signingCert = ks.getCertificate("user"); 174 validatingKey = signingCert.getPublicKey(); 175 176 // create common objects 177 withoutComments = fac.newCanonicalizationMethod 178 (CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null); 179 dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null); 180 dsaSha256 = fac.newSignatureMethod(DSA_SHA256, null); 181 sha1 = fac.newDigestMethod(DigestMethod.SHA1, null); 182 sha256 = fac.newDigestMethod(DigestMethod.SHA256, null); 183 sha384 = fac.newDigestMethod 184 ("http://www.w3.org/2001/04/xmldsig-more#sha384", null); 185 sha512 = fac.newDigestMethod(DigestMethod.SHA512, null); 186 dsa1024 = kifac.newKeyInfo(Collections.singletonList 187 (kifac.newKeyValue(validatingKey))); 188 dsa2048 = kifac.newKeyInfo(Collections.singletonList 189 (kifac.newKeyValue(getPublicKey("DSA", 2048)))); 190 rsa = kifac.newKeyInfo(Collections.singletonList 191 (kifac.newKeyValue(getPublicKey("RSA", 512)))); 192 rsa1024 = kifac.newKeyInfo(Collections.singletonList 193 (kifac.newKeyValue(getPublicKey("RSA", 1024)))); 194 p256ki = kifac.newKeyInfo(Collections.singletonList 195 (kifac.newKeyValue(getECPublicKey("P256")))); 196 p384ki = kifac.newKeyInfo(Collections.singletonList 197 (kifac.newKeyValue(getECPublicKey("P384")))); 198 p521ki = kifac.newKeyInfo(Collections.singletonList 199 (kifac.newKeyValue(getECPublicKey("P521")))); 200 rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null); 201 rsaSha256 = fac.newSignatureMethod 202 ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null); 203 rsaSha384 = fac.newSignatureMethod 204 ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384", null); 205 rsaSha512 = fac.newSignatureMethod 206 ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512", null); 207 ecdsaSha1 = fac.newSignatureMethod 208 ("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1", null); 209 sks = new KeySelectors.SecretKeySelector("secret".getBytes("ASCII")); 210 211 httpUd = new HttpURIDereferencer(); 212 } 213 214 static void test_create_signature_enveloped_dsa(int size) throws Exception { 215 System.out.println("* Generating signature-enveloped-dsa-" 216 + size + ".xml"); 217 SignatureMethod sm = null; 218 KeyInfo ki = null; 219 Key privKey; 220 if (size == 1024) { 221 sm = dsaSha1; 222 ki = dsa1024; 223 privKey = signingKey; 224 } else if (size == 2048) { 225 sm = dsaSha256; 226 ki = dsa2048; 227 privKey = getPrivateKey("DSA", 2048); 228 } else throw new RuntimeException("unsupported keysize:" + size); 229 230 // create SignedInfo 231 SignedInfo si = fac.newSignedInfo 232 (withoutComments, sm, Collections.singletonList 233 (fac.newReference 234 ("", sha1, Collections.singletonList 235 (fac.newTransform(Transform.ENVELOPED, 236 (TransformParameterSpec) null)), 237 null, null))); 238 239 // create XMLSignature 240 XMLSignature sig = fac.newXMLSignature(si, ki); 241 242 Document doc = db.newDocument(); 243 Element envelope = doc.createElementNS 244 ("http://example.org/envelope", "Envelope"); 245 envelope.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, 246 "xmlns", "http://example.org/envelope"); 247 doc.appendChild(envelope); 248 249 DOMSignContext dsc = new DOMSignContext(privKey, envelope); 250 251 sig.sign(dsc); 252 // StringWriter sw = new StringWriter(); 253 // dumpDocument(doc, sw); 254 // System.out.println(sw.toString()); 255 256 DOMValidateContext dvc = new DOMValidateContext 257 (kvks, envelope.getFirstChild()); 258 XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); 259 260 if (sig.equals(sig2) == false) { 261 throw new Exception 262 ("Unmarshalled signature is not equal to generated signature"); 263 } 264 265 if (sig2.validate(dvc) == false) { 266 throw new Exception("Validation of generated signature failed"); 267 } 268 System.out.println(); 269 } 270 271 static void test_create_signature_enveloping_b64_dsa() throws Exception { 272 System.out.println("* Generating signature-enveloping-b64-dsa.xml"); 273 test_create_signature_enveloping 274 (sha1, dsaSha1, dsa1024, signingKey, kvks, true); 275 System.out.println(); 276 } 277 278 static void test_create_signature_enveloping_dsa() throws Exception { 279 System.out.println("* Generating signature-enveloping-dsa.xml"); 280 test_create_signature_enveloping 281 (sha1, dsaSha1, dsa1024, signingKey, kvks, false); 282 System.out.println(); 283 } 284 285 static void test_create_signature_enveloping_sha256_dsa() throws Exception { 286 System.out.println("* Generating signature-enveloping-sha256-dsa.xml"); 287 test_create_signature_enveloping 288 (sha256, dsaSha1, dsa1024, signingKey, kvks, false); 289 System.out.println(); 290 } 291 292 static void test_create_signature_enveloping_hmac_sha1_40() 293 throws Exception { 294 System.out.println("* Generating signature-enveloping-hmac-sha1-40.xml"); 295 SignatureMethod hmacSha1 = fac.newSignatureMethod 296 (SignatureMethod.HMAC_SHA1, new HMACParameterSpec(40)); 297 try { 298 test_create_signature_enveloping(sha1, hmacSha1, null, 299 getSecretKey("secret".getBytes("ASCII")), sks, false); 300 } catch (Exception e) { 301 if (!(e instanceof XMLSignatureException)) { 302 throw e; 303 } 304 } 305 System.out.println(); 306 } 307 308 static void test_create_signature_enveloping_hmac_sha256() 309 throws Exception { 310 System.out.println("* Generating signature-enveloping-hmac-sha256.xml"); 311 SignatureMethod hmacSha256 = fac.newSignatureMethod 312 ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", null); 313 test_create_signature_enveloping(sha1, hmacSha256, null, 314 getSecretKey("secret".getBytes("ASCII")), sks, false); 315 System.out.println(); 316 } 317 318 static void test_create_signature_enveloping_hmac_sha384() 319 throws Exception { 320 System.out.println("* Generating signature-enveloping-hmac-sha384.xml"); 321 SignatureMethod hmacSha384 = fac.newSignatureMethod 322 ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", null); 323 test_create_signature_enveloping(sha1, hmacSha384, null, 324 getSecretKey("secret".getBytes("ASCII")), sks, false); 325 System.out.println(); 326 } 327 328 static void test_create_signature_enveloping_hmac_sha512() 329 throws Exception { 330 System.out.println("* Generating signature-enveloping-hmac-sha512.xml"); 331 SignatureMethod hmacSha512 = fac.newSignatureMethod 332 ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", null); 333 test_create_signature_enveloping(sha1, hmacSha512, null, 334 getSecretKey("secret".getBytes("ASCII")), sks, false); 335 System.out.println(); 336 } 337 338 static void test_create_signature_enveloping_rsa() throws Exception { 339 System.out.println("* Generating signature-enveloping-rsa.xml"); 340 test_create_signature_enveloping(sha1, rsaSha1, rsa, 341 getPrivateKey("RSA", 512), kvks, false); 342 System.out.println(); 343 } 344 345 static void test_create_signature_enveloping_sha384_rsa_sha256() 346 throws Exception { 347 System.out.println("* Generating signature-enveloping-sha384-rsa_sha256.xml"); 348 test_create_signature_enveloping(sha384, rsaSha256, rsa, 349 getPrivateKey("RSA", 512), kvks, false); 350 System.out.println(); 351 } 352 353 static void test_create_signature_enveloping_sha512_rsa_sha384() 354 throws Exception { 355 System.out.println("* Generating signature-enveloping-sha512-rsa_sha384.xml"); 356 test_create_signature_enveloping(sha512, rsaSha384, rsa1024, 357 getPrivateKey("RSA", 1024), kvks, false); 358 System.out.println(); 359 } 360 361 static void test_create_signature_enveloping_sha512_rsa_sha512() 362 throws Exception { 363 System.out.println("* Generating signature-enveloping-sha512-rsa_sha512.xml"); 364 test_create_signature_enveloping(sha512, rsaSha512, rsa1024, 365 getPrivateKey("RSA", 1024), kvks, false); 366 System.out.println(); 367 } 368 369 static void test_create_signature_enveloping_p256_sha1() throws Exception { 370 System.out.println("* Generating signature-enveloping-p256-sha1.xml"); 371 test_create_signature_enveloping(sha1, ecdsaSha1, p256ki, 372 getECPrivateKey("P256"), kvks, false); 373 System.out.println(); 374 } 375 376 static void test_create_signature_enveloping_p384_sha1() throws Exception { 377 System.out.println("* Generating signature-enveloping-p384-sha1.xml"); 378 test_create_signature_enveloping(sha1, ecdsaSha1, p384ki, 379 getECPrivateKey("P384"), kvks, false); 380 System.out.println(); 381 } 382 383 static void test_create_signature_enveloping_p521_sha1() throws Exception { 384 System.out.println("* Generating signature-enveloping-p521-sha1.xml"); 385 test_create_signature_enveloping(sha1, ecdsaSha1, p521ki, 386 getECPrivateKey("P521"), kvks, false); 387 System.out.println(); 388 } 389 390 static void test_create_signature_external_b64_dsa() throws Exception { 391 System.out.println("* Generating signature-external-b64-dsa.xml"); 392 test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, true); 393 System.out.println(); 394 } 395 396 static void test_create_signature_external_dsa() throws Exception { 397 System.out.println("* Generating signature-external-dsa.xml"); 398 test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, false); 399 System.out.println(); 400 } 401 402 static void test_create_signature_keyname() throws Exception { 403 System.out.println("* Generating signature-keyname.xml"); 404 KeyInfo kn = kifac.newKeyInfo(Collections.singletonList 405 (kifac.newKeyName("user"))); 406 test_create_signature_external(dsaSha1, kn, signingKey, 407 new X509KeySelector(ks), false); 408 System.out.println(); 409 } 410 411 static void test_create_signature_retrievalmethod_rawx509crt() 412 throws Exception { 413 System.out.println( 414 "* Generating signature-retrievalmethod-rawx509crt.xml"); 415 KeyInfo rm = kifac.newKeyInfo(Collections.singletonList 416 (kifac.newRetrievalMethod 417 ("certs/user.crt", X509Data.RAW_X509_CERTIFICATE_TYPE, null))); 418 test_create_signature_external(dsaSha1, rm, signingKey, 419 new X509KeySelector(ks), false); 420 System.out.println(); 421 } 422 423 static void test_create_signature_x509_crt_crl() throws Exception { 424 System.out.println("* Generating signature-x509-crt-crl.xml"); 425 List<Object> xds = new ArrayList<>(); 426 CertificateFactory cf = CertificateFactory.getInstance("X.509"); 427 xds.add(signingCert); 428 FileInputStream fis = new FileInputStream(CRL); 429 X509CRL crl = (X509CRL) cf.generateCRL(fis); 430 fis.close(); 431 xds.add(crl); 432 KeyInfo crt_crl = kifac.newKeyInfo(Collections.singletonList 433 (kifac.newX509Data(xds))); 434 435 test_create_signature_external(dsaSha1, crt_crl, signingKey, 436 new X509KeySelector(ks), false); 437 System.out.println(); 438 } 439 440 static void test_create_signature_x509_crt() throws Exception { 441 System.out.println("* Generating signature-x509-crt.xml"); 442 KeyInfo crt = kifac.newKeyInfo(Collections.singletonList 443 (kifac.newX509Data(Collections.singletonList(signingCert)))); 444 445 test_create_signature_external(dsaSha1, crt, signingKey, 446 new X509KeySelector(ks), false); 447 System.out.println(); 448 } 449 450 static void test_create_signature_x509_is() throws Exception { 451 System.out.println("* Generating signature-x509-is.xml"); 452 KeyInfo is = kifac.newKeyInfo(Collections.singletonList 453 (kifac.newX509Data(Collections.singletonList 454 (kifac.newX509IssuerSerial 455 ("CN=User", new BigInteger("45ef2729", 16)))))); 456 test_create_signature_external(dsaSha1, is, signingKey, 457 new X509KeySelector(ks), false); 458 System.out.println(); 459 } 460 461 static void test_create_signature_x509_ski() throws Exception { 462 System.out.println("* Generating signature-x509-ski.xml"); 463 KeyInfo ski = kifac.newKeyInfo(Collections.singletonList 464 (kifac.newX509Data(Collections.singletonList 465 ("keyid".getBytes("ASCII"))))); 466 467 test_create_signature_external(dsaSha1, ski, signingKey, 468 KeySelector.singletonKeySelector(validatingKey), false); 469 System.out.println(); 470 } 471 472 static void test_create_signature_x509_sn() throws Exception { 473 System.out.println("* Generating signature-x509-sn.xml"); 474 KeyInfo sn = kifac.newKeyInfo(Collections.singletonList 475 (kifac.newX509Data(Collections.singletonList("CN=User")))); 476 477 test_create_signature_external(dsaSha1, sn, signingKey, 478 new X509KeySelector(ks), false); 479 System.out.println(); 480 } 481 482 static void test_create_signature_reference_dependency() throws Exception { 483 System.out.println("* Generating signature-reference-dependency.xml"); 484 // create references 485 List<Reference> refs = Collections.singletonList 486 (fac.newReference("#object-1", sha1)); 487 488 // create SignedInfo 489 SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs); 490 491 // create objects 492 List<XMLObject> objs = new ArrayList<>(); 493 494 // Object 1 495 List<Reference> manRefs = Collections.singletonList 496 (fac.newReference("#object-2", sha1)); 497 objs.add(fac.newXMLObject(Collections.singletonList 498 (fac.newManifest(manRefs, "manifest-1")), "object-1", null, null)); 499 500 // Object 2 501 Document doc = db.newDocument(); 502 Element nc = doc.createElementNS(null, "NonCommentandus"); 503 nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", ""); 504 nc.appendChild(doc.createComment(" Commentandum ")); 505 objs.add(fac.newXMLObject(Collections.singletonList 506 (new DOMStructure(nc)), "object-2", null, null)); 507 508 // create XMLSignature 509 XMLSignature sig = fac.newXMLSignature(si, rsa, objs, "signature", null); 510 DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc); 511 512 sig.sign(dsc); 513 514 // dumpDocument(doc, new PrintWriter(System.out)); 515 516 DOMValidateContext dvc = new DOMValidateContext 517 (kvks, doc.getDocumentElement()); 518 XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); 519 520 if (sig.equals(sig2) == false) { 521 throw new Exception 522 ("Unmarshalled signature is not equal to generated signature"); 523 } 524 if (sig2.validate(dvc) == false) { 525 throw new Exception("Validation of generated signature failed"); 526 } 527 528 System.out.println(); 529 } 530 531 static void test_create_signature_with_attr_in_no_namespace() 532 throws Exception 533 { 534 System.out.println 535 ("* Generating signature-with-attr-in-no-namespace.xml"); 536 537 // create references 538 List<Reference> refs = Collections.singletonList 539 (fac.newReference("#unknown", sha1)); 540 541 // create SignedInfo 542 SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs); 543 544 // create object-1 545 Document doc = db.newDocument(); 546 Element nc = doc.createElementNS(null, "NonCommentandus"); 547 // add attribute with no namespace 548 nc.setAttribute("Id", "unknown"); 549 XMLObject obj = fac.newXMLObject(Collections.singletonList 550 (new DOMStructure(nc)), "object-1", null, null); 551 552 // create XMLSignature 553 XMLSignature sig = fac.newXMLSignature(si, rsa, 554 Collections.singletonList(obj), 555 "signature", null); 556 DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc); 557 dsc.setIdAttributeNS(nc, null, "Id"); 558 559 sig.sign(dsc); 560 561 // dumpDocument(doc, new PrintWriter(System.out)); 562 563 DOMValidateContext dvc = new DOMValidateContext 564 (kvks, doc.getDocumentElement()); 565 dvc.setIdAttributeNS(nc, null, "Id"); 566 XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); 567 568 if (sig.equals(sig2) == false) { 569 throw new Exception 570 ("Unmarshalled signature is not equal to generated signature"); 571 } 572 if (sig2.validate(dvc) == false) { 573 throw new Exception("Validation of generated signature failed"); 574 } 575 576 System.out.println(); 577 } 578 579 static void test_create_signature_with_empty_id() throws Exception { 580 System.out.println("* Generating signature-with-empty-id.xml"); 581 582 // create references 583 List<Reference> refs = Collections.singletonList 584 (fac.newReference("#", sha1)); 585 586 // create SignedInfo 587 SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs); 588 589 // create object with empty id 590 Document doc = db.newDocument(); 591 XMLObject obj = fac.newXMLObject(Collections.singletonList 592 (new DOMStructure(doc.createTextNode("I am the text."))), 593 "", "text/plain", null); 594 595 // create XMLSignature 596 XMLSignature sig = fac.newXMLSignature(si, rsa, 597 Collections.singletonList(obj), 598 "signature", null); 599 DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc); 600 sig.sign(dsc); 601 } 602 603 static void test_create_signature() throws Exception { 604 System.out.println("* Generating signature.xml"); 605 606 // create references 607 List<Reference> refs = new ArrayList<>(); 608 609 // Reference 1 610 refs.add(fac.newReference(STYLESHEET, sha1)); 611 612 // Reference 2 613 refs.add(fac.newReference 614 (STYLESHEET_B64, 615 sha1, Collections.singletonList 616 (fac.newTransform(Transform.BASE64, 617 (TransformParameterSpec) null)), null, null)); 618 619 // Reference 3 620 refs.add(fac.newReference("#object-1", sha1, Collections.singletonList 621 (fac.newTransform(Transform.XPATH, 622 new XPathFilterParameterSpec("self::text()"))), 623 XMLObject.TYPE, null)); 624 625 // Reference 4 626 String expr = "\n" 627 + " ancestor-or-self::dsig:SignedInfo " + "\n" 628 + " and " + "\n" 629 + " count(ancestor-or-self::dsig:Reference | " + "\n" 630 + " here()/ancestor::dsig:Reference[1]) > " + "\n" 631 + " count(ancestor-or-self::dsig:Reference) " + "\n" 632 + " or " + "\n" 633 + " count(ancestor-or-self::node() | " + "\n" 634 + " id('notaries')) = " + "\n" 635 + " count(ancestor-or-self::node()) " + "\n"; 636 637 XPathFilterParameterSpec xfp = new XPathFilterParameterSpec(expr, 638 Collections.singletonMap("dsig", XMLSignature.XMLNS)); 639 refs.add(fac.newReference("", sha1, Collections.singletonList 640 (fac.newTransform(Transform.XPATH, xfp)), 641 XMLObject.TYPE, null)); 642 643 // Reference 5 644 refs.add(fac.newReference("#object-2", sha1, Collections.singletonList 645 (fac.newTransform 646 (Transform.BASE64, (TransformParameterSpec) null)), 647 XMLObject.TYPE, null)); 648 649 // Reference 6 650 refs.add(fac.newReference 651 ("#manifest-1", sha1, null, Manifest.TYPE, null)); 652 653 // Reference 7 654 refs.add(fac.newReference("#signature-properties-1", sha1, null, 655 SignatureProperties.TYPE, null)); 656 657 // Reference 8 658 List<Transform> transforms = new ArrayList<>(); 659 transforms.add(fac.newTransform 660 (Transform.ENVELOPED, (TransformParameterSpec) null)); 661 refs.add(fac.newReference("", sha1, transforms, null, null)); 662 663 // Reference 9 664 transforms.add(fac.newTransform 665 (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, 666 (TransformParameterSpec) null)); 667 refs.add(fac.newReference("", sha1, transforms, null, null)); 668 669 // Reference 10 670 Transform env = fac.newTransform 671 (Transform.ENVELOPED, (TransformParameterSpec) null); 672 refs.add(fac.newReference("#xpointer(/)", 673 sha1, Collections.singletonList(env), null, null)); 674 675 // Reference 11 676 transforms.clear(); 677 transforms.add(fac.newTransform 678 (Transform.ENVELOPED, (TransformParameterSpec) null)); 679 transforms.add(fac.newTransform 680 (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, 681 (TransformParameterSpec) null)); 682 refs.add(fac.newReference("#xpointer(/)", sha1, transforms, 683 null, null)); 684 685 // Reference 12 686 refs.add 687 (fac.newReference("#object-3", sha1, null, XMLObject.TYPE, null)); 688 689 // Reference 13 690 Transform withComments = fac.newTransform 691 (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, 692 (TransformParameterSpec) null); 693 refs.add(fac.newReference("#object-3", sha1, 694 Collections.singletonList(withComments), XMLObject.TYPE, null)); 695 696 // Reference 14 697 refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, null, 698 XMLObject.TYPE, null)); 699 700 // Reference 15 701 withComments = fac.newTransform 702 (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, 703 (TransformParameterSpec) null); 704 refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, 705 Collections.singletonList(withComments), XMLObject.TYPE, null)); 706 707 // Reference 16 708 refs.add(fac.newReference("#reference-2", sha1)); 709 710 // Reference 17 711 refs.add(fac.newReference("#manifest-reference-1", sha1, null, 712 null, "reference-1")); 713 714 // Reference 18 715 refs.add(fac.newReference("#reference-1", sha1, null, null, 716 "reference-2")); 717 718 // create SignedInfo 719 SignedInfo si = fac.newSignedInfo(withoutComments, dsaSha1, refs); 720 721 // create keyinfo 722 XPathFilterParameterSpec xpf = new XPathFilterParameterSpec( 723 "ancestor-or-self::dsig:X509Data", 724 Collections.singletonMap("dsig", XMLSignature.XMLNS)); 725 RetrievalMethod rm = kifac.newRetrievalMethod("#object-4", 726 X509Data.TYPE, Collections.singletonList(fac.newTransform 727 (Transform.XPATH, xpf))); 728 KeyInfo ki = kifac.newKeyInfo(Collections.singletonList(rm), null); 729 730 Document doc = db.newDocument(); 731 732 // create objects 733 List<XMLObject> objs = new ArrayList<>(); 734 735 // Object 1 736 objs.add(fac.newXMLObject(Collections.singletonList 737 (new DOMStructure(doc.createTextNode("I am the text."))), 738 "object-1", "text/plain", null)); 739 740 // Object 2 741 objs.add(fac.newXMLObject(Collections.singletonList 742 (new DOMStructure(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="))), 743 "object-2", "text/plain", Transform.BASE64)); 744 745 // Object 3 746 Element nc = doc.createElementNS(null, "NonCommentandus"); 747 nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", ""); 748 nc.appendChild(doc.createComment(" Commentandum ")); 749 objs.add(fac.newXMLObject(Collections.singletonList 750 (new DOMStructure(nc)), "object-3", null, null)); 751 752 // Manifest 753 List<Reference> manRefs = new ArrayList<>(); 754 755 // Manifest Reference 1 756 manRefs.add(fac.newReference(STYLESHEET, 757 sha1, null, null, "manifest-reference-1")); 758 759 // Manifest Reference 2 760 manRefs.add(fac.newReference("#reference-1", sha1)); 761 762 // Manifest Reference 3 763 List<Transform> manTrans = new ArrayList<>(); 764 String xslt = "" 765 + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'\n" 766 + " xmlns='http://www.w3.org/TR/xhtml1/strict' \n" 767 + " exclude-result-prefixes='foo' \n" 768 + " version='1.0'>\n" 769 + " <xsl:output encoding='UTF-8' \n" 770 + " indent='no' \n" 771 + " method='xml' />\n" 772 + " <xsl:template match='/'>\n" 773 + " <html>\n" 774 + " <head>\n" 775 + " <title>Notaries</title>\n" 776 + " </head>\n" 777 + " <body>\n" 778 + " <table>\n" 779 + " <xsl:for-each select='Notaries/Notary'>\n" 780 + " <tr>\n" 781 + " <th>\n" 782 + " <xsl:value-of select='@name' />\n" 783 + " </th>\n" 784 + " </tr>\n" 785 + " </xsl:for-each>\n" 786 + " </table>\n" 787 + " </body>\n" 788 + " </html>\n" 789 + " </xsl:template>\n" 790 + "</xsl:stylesheet>\n"; 791 Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes())); 792 Node xslElem = docxslt.getDocumentElement(); 793 794 manTrans.add(fac.newTransform(Transform.XSLT, 795 new XSLTTransformParameterSpec(new DOMStructure(xslElem)))); 796 manTrans.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE, 797 (TransformParameterSpec) null)); 798 manRefs.add(fac.newReference("#notaries", sha1, manTrans, null, null)); 799 800 objs.add(fac.newXMLObject(Collections.singletonList 801 (fac.newManifest(manRefs, "manifest-1")), null, null, null)); 802 803 // SignatureProperties 804 Element sa = doc.createElementNS("urn:demo", "SignerAddress"); 805 sa.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:demo"); 806 Element ip = doc.createElementNS("urn:demo", "IP"); 807 ip.appendChild(doc.createTextNode("192.168.21.138")); 808 sa.appendChild(ip); 809 SignatureProperty sp = fac.newSignatureProperty 810 (Collections.singletonList(new DOMStructure(sa)), 811 "#signature", null); 812 SignatureProperties sps = fac.newSignatureProperties 813 (Collections.singletonList(sp), "signature-properties-1"); 814 objs.add(fac.newXMLObject(Collections.singletonList(sps), null, 815 null, null)); 816 817 // Object 4 818 List<Object> xds = new ArrayList<>(); 819 xds.add("CN=User"); 820 xds.add(kifac.newX509IssuerSerial 821 ("CN=User", new BigInteger("45ef2729", 16))); 822 xds.add(signingCert); 823 objs.add(fac.newXMLObject(Collections.singletonList 824 (kifac.newX509Data(xds)), "object-4", null, null)); 825 826 // create XMLSignature 827 XMLSignature sig = fac.newXMLSignature(si, ki, objs, "signature", null); 828 829 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 830 dbf.setNamespaceAware(true); 831 dbf.setValidating(false); 832 Document envDoc = dbf.newDocumentBuilder().parse 833 (new FileInputStream(ENVELOPE)); 834 Element ys = (Element) 835 envDoc.getElementsByTagName("YoursSincerely").item(0); 836 837 DOMSignContext dsc = new DOMSignContext(signingKey, ys); 838 dsc.setURIDereferencer(httpUd); 839 840 sig.sign(dsc); 841 842 // StringWriter sw = new StringWriter(); 843 // dumpDocument(envDoc, sw); 844 845 NodeList nl = 846 envDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); 847 if (nl.getLength() == 0) { 848 throw new Exception("Couldn't find signature Element"); 849 } 850 Element sigElement = (Element) nl.item(0); 851 852 DOMValidateContext dvc = new DOMValidateContext 853 (new X509KeySelector(ks), sigElement); 854 dvc.setURIDereferencer(httpUd); 855 File f = new File( 856 System.getProperty("dir.test.vector.baltimore") + 857 System.getProperty("file.separator") + 858 "merlin-xmldsig-twenty-three" + 859 System.getProperty("file.separator")); 860 dvc.setBaseURI(f.toURI().toString()); 861 862 XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); 863 864 if (sig.equals(sig2) == false) { 865 throw new Exception 866 ("Unmarshalled signature is not equal to generated signature"); 867 } 868 if (sig2.validate(dvc) == false) { 869 throw new Exception("Validation of generated signature failed"); 870 } 871 System.out.println(); 872 } 873 874 private static void dumpDocument(Document doc, Writer w) throws Exception { 875 TransformerFactory tf = TransformerFactory.newInstance(); 876 Transformer trans = tf.newTransformer(); 877 // trans.setOutputProperty(OutputKeys.INDENT, "yes"); 878 trans.transform(new DOMSource(doc), new StreamResult(w)); 879 } 880 881 private static void test_create_signature_external 882 (SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks, 883 boolean b64) throws Exception { 884 885 // create reference 886 Reference ref; 887 if (b64) { 888 ref = fac.newReference 889 (STYLESHEET_B64, 890 sha1, Collections.singletonList 891 (fac.newTransform(Transform.BASE64, 892 (TransformParameterSpec) null)), null, null); 893 } else { 894 ref = fac.newReference(STYLESHEET, sha1); 895 } 896 897 // create SignedInfo 898 SignedInfo si = fac.newSignedInfo(withoutComments, sm, 899 Collections.singletonList(ref)); 900 901 Document doc = db.newDocument(); 902 903 // create XMLSignature 904 XMLSignature sig = fac.newXMLSignature(si, ki); 905 906 DOMSignContext dsc = new DOMSignContext(signingKey, doc); 907 dsc.setURIDereferencer(httpUd); 908 909 sig.sign(dsc); 910 911 DOMValidateContext dvc = new DOMValidateContext 912 (ks, doc.getDocumentElement()); 913 File f = new File(DATA_DIR); 914 dvc.setBaseURI(f.toURI().toString()); 915 dvc.setURIDereferencer(httpUd); 916 917 XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); 918 919 if (sig.equals(sig2) == false) { 920 throw new Exception 921 ("Unmarshalled signature is not equal to generated signature"); 922 } 923 if (sig2.validate(dvc) == false) { 924 throw new Exception("Validation of generated signature failed"); 925 } 926 } 927 928 private static void test_create_signature_enveloping 929 (DigestMethod dm, SignatureMethod sm, KeyInfo ki, Key signingKey, 930 KeySelector ks, boolean b64) throws Exception { 931 932 // create reference 933 Reference ref; 934 if (b64) { 935 ref = fac.newReference("#object", dm, Collections.singletonList 936 (fac.newTransform(Transform.BASE64, 937 (TransformParameterSpec) null)), null, null); 938 } else { 939 ref = fac.newReference("#object", dm); 940 } 941 942 // create SignedInfo 943 SignedInfo si = fac.newSignedInfo(withoutComments, sm, 944 Collections.singletonList(ref)); 945 946 Document doc = db.newDocument(); 947 // create Objects 948 String text = b64 ? "c29tZSB0ZXh0" : "some text"; 949 XMLObject obj = fac.newXMLObject(Collections.singletonList 950 (new DOMStructure(doc.createTextNode(text))), 951 "object", null, null); 952 953 // create XMLSignature 954 XMLSignature sig = fac.newXMLSignature 955 (si, ki, Collections.singletonList(obj), null, null); 956 957 DOMSignContext dsc = new DOMSignContext(signingKey, doc); 958 959 sig.sign(dsc); 960 961 // dumpDocument(doc, new FileWriter("/tmp/foo.xml")); 962 963 DOMValidateContext dvc = new DOMValidateContext 964 (ks, doc.getDocumentElement()); 965 XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); 966 967 if (sig.equals(sig2) == false) { 968 throw new Exception 969 ("Unmarshalled signature is not equal to generated signature"); 970 } 971 if (sig2.validate(dvc) == false) { 972 throw new Exception("Validation of generated signature failed"); 973 } 974 } 975 976 static void test_create_exc_signature() throws Exception { 977 System.out.println("* Generating exc_signature.xml"); 978 List<Reference> refs = new ArrayList<>(4); 979 980 // create reference 1 981 refs.add(fac.newReference 982 ("#xpointer(id('to-be-signed'))", 983 fac.newDigestMethod(DigestMethod.SHA1, null), 984 Collections.singletonList 985 (fac.newTransform(CanonicalizationMethod.EXCLUSIVE, 986 (TransformParameterSpec) null)), 987 null, null)); 988 989 // create reference 2 990 List<String> prefixList = new ArrayList<>(2); 991 prefixList.add("bar"); 992 prefixList.add("#default"); 993 ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList); 994 refs.add(fac.newReference 995 ("#xpointer(id('to-be-signed'))", 996 fac.newDigestMethod(DigestMethod.SHA1, null), 997 Collections.singletonList 998 (fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)), 999 null, null)); 1000 1001 // create reference 3 1002 refs.add(fac.newReference 1003 ("#xpointer(id('to-be-signed'))", 1004 fac.newDigestMethod(DigestMethod.SHA1, null), 1005 Collections.singletonList(fac.newTransform 1006 (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, 1007 (TransformParameterSpec) null)), 1008 null, null)); 1009 1010 // create reference 4 1011 prefixList = new ArrayList<>(2); 1012 prefixList.add("bar"); 1013 prefixList.add("#default"); 1014 params = new ExcC14NParameterSpec(prefixList); 1015 refs.add(fac.newReference 1016 ("#xpointer(id('to-be-signed'))", 1017 fac.newDigestMethod(DigestMethod.SHA1, null), 1018 Collections.singletonList(fac.newTransform 1019 (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)), 1020 null, null)); 1021 1022 // create SignedInfo 1023 SignedInfo si = fac.newSignedInfo( 1024 fac.newCanonicalizationMethod 1025 (CanonicalizationMethod.EXCLUSIVE, 1026 (C14NMethodParameterSpec) null), 1027 fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs); 1028 1029 // create KeyInfo 1030 List<XMLStructure> kits = new ArrayList<>(2); 1031 kits.add(kifac.newKeyValue(validatingKey)); 1032 KeyInfo ki = kifac.newKeyInfo(kits); 1033 1034 // create Objects 1035 Document doc = db.newDocument(); 1036 Element baz = doc.createElementNS("urn:bar", "bar:Baz"); 1037 Comment com = doc.createComment(" comment "); 1038 baz.appendChild(com); 1039 XMLObject obj = fac.newXMLObject(Collections.singletonList 1040 (new DOMStructure(baz)), "to-be-signed", null, null); 1041 1042 // create XMLSignature 1043 XMLSignature sig = fac.newXMLSignature 1044 (si, ki, Collections.singletonList(obj), null, null); 1045 1046 Element foo = doc.createElementNS("urn:foo", "Foo"); 1047 foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo"); 1048 foo.setAttributeNS 1049 ("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar"); 1050 doc.appendChild(foo); 1051 1052 DOMSignContext dsc = new DOMSignContext(signingKey, foo); 1053 dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig"); 1054 1055 sig.sign(dsc); 1056 1057 // dumpDocument(doc, new FileWriter("/tmp/foo.xml")); 1058 1059 DOMValidateContext dvc = new DOMValidateContext 1060 (new KeySelectors.KeyValueKeySelector(), foo.getLastChild()); 1061 XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); 1062 1063 if (sig.equals(sig2) == false) { 1064 throw new Exception 1065 ("Unmarshalled signature is not equal to generated signature"); 1066 } 1067 if (sig2.validate(dvc) == false) { 1068 throw new Exception("Validation of generated signature failed"); 1069 } 1070 System.out.println(); 1071 } 1072 1073 static void test_create_sign_spec() throws Exception { 1074 System.out.println("* Generating sign-spec.xml"); 1075 List<Reference> refs = new ArrayList<>(2); 1076 1077 // create reference 1 1078 List<XPathType> types = new ArrayList<>(3); 1079 types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT)); 1080 types.add(new XPathType(" //NotToBeSigned ", 1081 XPathType.Filter.SUBTRACT)); 1082 types.add(new XPathType(" //ReallyToBeSigned ", 1083 XPathType.Filter.UNION)); 1084 XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types); 1085 refs.add(fac.newReference 1086 ("", fac.newDigestMethod(DigestMethod.SHA1, null), 1087 Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)), 1088 null, null)); 1089 1090 // create reference 2 1091 List<Transform> trans2 = new ArrayList<>(2); 1092 trans2.add(fac.newTransform(Transform.ENVELOPED, 1093 (TransformParameterSpec) null)); 1094 XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec 1095 (Collections.singletonList 1096 (new XPathType(" / ", XPathType.Filter.UNION))); 1097 trans2.add(fac.newTransform(Transform.XPATH2, xp2)); 1098 refs.add(fac.newReference("#signature-value", 1099 fac.newDigestMethod(DigestMethod.SHA1, null), trans2, null, null)); 1100 1101 // create SignedInfo 1102 SignedInfo si = fac.newSignedInfo( 1103 fac.newCanonicalizationMethod 1104 (CanonicalizationMethod.INCLUSIVE, 1105 (C14NMethodParameterSpec) null), 1106 fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs); 1107 1108 // create KeyInfo 1109 List<XMLStructure> kits = new ArrayList<>(2); 1110 kits.add(kifac.newKeyValue(validatingKey)); 1111 List<Object> xds = new ArrayList<>(2); 1112 xds.add("CN=User"); 1113 xds.add(signingCert); 1114 kits.add(kifac.newX509Data(xds)); 1115 KeyInfo ki = kifac.newKeyInfo(kits); 1116 1117 // create XMLSignature 1118 XMLSignature sig = fac.newXMLSignature 1119 (si, ki, null, null, "signature-value"); 1120 1121 Document doc = db.newDocument(); 1122 Element tbs1 = doc.createElementNS(null, "ToBeSigned"); 1123 Comment tbs1Com = doc.createComment(" comment "); 1124 Element tbs1Data = doc.createElementNS(null, "Data"); 1125 Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned"); 1126 Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned"); 1127 Comment tbs1rtbsCom = doc.createComment(" comment "); 1128 Element tbs1rtbsData = doc.createElementNS(null, "Data"); 1129 tbs1rtbs.appendChild(tbs1rtbsCom); 1130 tbs1rtbs.appendChild(tbs1rtbsData); 1131 tbs1ntbs.appendChild(tbs1rtbs); 1132 tbs1.appendChild(tbs1Com); 1133 tbs1.appendChild(tbs1Data); 1134 tbs1.appendChild(tbs1ntbs); 1135 1136 Element tbs2 = doc.createElementNS(null, "ToBeSigned"); 1137 Element tbs2Data = doc.createElementNS(null, "Data"); 1138 Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned"); 1139 Element tbs2ntbsData = doc.createElementNS(null, "Data"); 1140 tbs2ntbs.appendChild(tbs2ntbsData); 1141 tbs2.appendChild(tbs2Data); 1142 tbs2.appendChild(tbs2ntbs); 1143 1144 Element document = doc.createElementNS(null, "Document"); 1145 document.appendChild(tbs1); 1146 document.appendChild(tbs2); 1147 doc.appendChild(document); 1148 1149 DOMSignContext dsc = new DOMSignContext(signingKey, document); 1150 1151 sig.sign(dsc); 1152 1153 // dumpDocument(doc, new FileWriter("/tmp/foo.xml")); 1154 1155 DOMValidateContext dvc = new DOMValidateContext 1156 (new KeySelectors.KeyValueKeySelector(), document.getLastChild()); 1157 XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); 1158 1159 if (sig.equals(sig2) == false) { 1160 throw new Exception 1161 ("Unmarshalled signature is not equal to generated signature"); 1162 } 1163 if (sig2.validate(dvc) == false) { 1164 throw new Exception("Validation of generated signature failed"); 1165 } 1166 System.out.println(); 1167 } 1168 1169 private static final String DSA_Y = 1170 "070662842167565771936588335128634396171789331656318483584455493822" + 1171 "400811200853331373030669235424928346190274044631949560438023934623" + 1172 "71310375123430985057160"; 1173 private static final String DSA_P = 1174 "013232376895198612407547930718267435757728527029623408872245156039" + 1175 "757713029036368719146452186041204237350521785240337048752071462798" + 1176 "273003935646236777459223"; 1177 private static final String DSA_Q = 1178 "0857393771208094202104259627990318636601332086981"; 1179 private static final String DSA_G = 1180 "054216440574364751416096484883257051280474283943804743768346673007" + 1181 "661082626139005426812890807137245973106730741193551360857959820973" + 1182 "90670890367185141189796"; 1183 private static final String DSA_X = 1184 "0527140396812450214498055937934275626078768840117"; 1185 private static final String DSA_2048_Y = 1186 "15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928"; 1187 private static final String DSA_2048_P = 1188 "18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359"; 1189 private static final String DSA_2048_Q = 1190 "19689526866605154788513693571065914024068069442724893395618704484701"; 1191 private static final String DSA_2048_G = 1192 "2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430"; 1193 private static final String DSA_2048_X = 1194 "14562787764977288900757387442281559936279834964901963465277698843172"; 1195 private static final String RSA_MOD = 1196 "010800185049102889923150759252557522305032794699952150943573164381" + 1197 "936603255999071981574575044810461362008102247767482738822150129277" + 1198 "490998033971789476107463"; 1199 private static final String RSA_PRIV = 1200 "016116973584421969795445996229612671947635798429212816611707210835" + 1201 "915586591340598683996088487065438751488342251960069575392056288063" + 1202 "6800379454345804879553"; 1203 private static final String RSA_PUB = "065537"; 1204 private static final String RSA_1024_MOD = "098871307553789439961130765" + 1205 "909423744508062468450669519128736624058048856940468016843888594585" + 1206 "322862378444314635412341974900625010364163960238734457710620107530" + 1207 "573945081856371709138380902553309075505688814637544923038853658690" + 1208 "857672483016239697038853418682988686871489963827000080098971762923" + 1209 "833614557257607521"; 1210 private static final String RSA_1024_PRIV = "03682574144968491431483287" + 1211 "297021581096848810374110568017963075809477047466189822987258068867" + 1212 "704855380407747867998863645890602646601140183818953428006646987710" + 1213 "237008997971129772408397621801631622129297063463868593083106979716" + 1214 "204903524890556839550490384015324575598723478554854070823335021842" + 1215 "210112348400928769"; 1216 private static final String EC_P256_X = 1217 "335863644451761614592446380116804721648611739647823420286081723541" + 1218 "6166183710"; 1219 private static final String EC_P256_Y = 1220 "951559601159729477487064127150143688502130342917782252098602422796" + 1221 "95457910701"; 1222 private static final String EC_P256_S = 1223 "425976209773168452211813225517384419928639977904006759709292218082" + 1224 "7440083936"; 1225 private static final ECParameterSpec EC_P256_PARAMS = initECParams( 1226 "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 1227 "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 1228 "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", 1229 "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", 1230 "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", 1231 "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", 1232 1 1233 ); 1234 private static final String EC_P384_X = 1235 "12144058647679082341340699736608428955270957565259459672517275506071643671835484144490620216582303669654008841724053"; 1236 private static final String EC_P384_Y = 1237 "18287745972107701566600963632634101287058332546756092926848497481238534346489545826483592906634896557151987868614320"; 1238 private static final String EC_P384_S = 1239 "10307785759830534742680442271492590599236624208247590184679565032330507874096079979152605984203102224450595283943382"; 1240 private static final ECParameterSpec EC_P384_PARAMS = initECParams( 1241 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", 1242 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", 1243 "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", 1244 "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", 1245 "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", 1246 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", 1247 1 1248 ); 1249 private static final String EC_P521_X = 1250 "4157918188927862838251799402582135611021257663417126086145819679867926857146776190737187582274664373117054717389603317411991660346043842712448912355335343997"; 1251 private static final String EC_P521_Y = 1252 "4102838062751704796157456866854813794620023146924181568434486703918224542844053923233919899911519054998554969832861957437850996213216829205401947264294066288"; 1253 private static final String EC_P521_S = 1254 "4857798533181496041050215963883119936300918353498701880968530610687256097257307590162398707429640390843595868713096292822034014722985178583665959048714417342"; 1255 private static final ECParameterSpec EC_P521_PARAMS = initECParams( 1256 "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 1257 "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 1258 "0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 1259 "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", 1260 "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", 1261 "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 1262 1 1263 ); 1264 1265 private static ECParameterSpec initECParams( 1266 String sfield, String a, String b, String gx, String gy, 1267 String n, int h) { 1268 ECField field = new ECFieldFp(bigInt(sfield)); 1269 EllipticCurve curve = new EllipticCurve(field, 1270 bigInt(a), bigInt(b)); 1271 ECPoint g = new ECPoint(bigInt(gx), bigInt(gy)); 1272 return new ECParameterSpec(curve, g, bigInt(n), h); 1273 } 1274 1275 private static BigInteger bigInt(String s) { 1276 return new BigInteger(s, 16); 1277 } 1278 private static PublicKey getPublicKey(String algo, int keysize) 1279 throws Exception { 1280 KeyFactory kf = KeyFactory.getInstance(algo); 1281 KeySpec kspec; 1282 if (algo.equalsIgnoreCase("DSA")) { 1283 if (keysize == 1024) { 1284 kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y), 1285 new BigInteger(DSA_P), 1286 new BigInteger(DSA_Q), 1287 new BigInteger(DSA_G)); 1288 } else if (keysize == 2048) { 1289 kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y), 1290 new BigInteger(DSA_2048_P), 1291 new BigInteger(DSA_2048_Q), 1292 new BigInteger(DSA_2048_G)); 1293 } else throw new RuntimeException("Unsupported keysize:" + keysize); 1294 } else if (algo.equalsIgnoreCase("RSA")) { 1295 if (keysize == 512) { 1296 kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD), 1297 new BigInteger(RSA_PUB)); 1298 } else if (keysize == 1024) { 1299 kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD), 1300 new BigInteger(RSA_PUB)); 1301 } else throw new RuntimeException("Unsupported keysize:" + keysize); 1302 } else throw new RuntimeException("Unsupported key algorithm " + algo); 1303 return kf.generatePublic(kspec); 1304 } 1305 1306 private static PublicKey getECPublicKey(String curve) throws Exception { 1307 KeyFactory kf = KeyFactory.getInstance("EC"); 1308 String x, y; 1309 ECParameterSpec params; 1310 switch (curve) { 1311 case "P256": 1312 x = EC_P256_X; 1313 y = EC_P256_Y; 1314 params = EC_P256_PARAMS; 1315 break; 1316 case "P384": 1317 x = EC_P384_X; 1318 y = EC_P384_Y; 1319 params = EC_P384_PARAMS; 1320 break; 1321 case "P521": 1322 x = EC_P521_X; 1323 y = EC_P521_Y; 1324 params = EC_P521_PARAMS; 1325 break; 1326 default: 1327 throw new Exception("Unsupported curve: " + curve); 1328 } 1329 KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), 1330 new BigInteger(y)), 1331 params); 1332 return kf.generatePublic(kspec); 1333 } 1334 1335 private static PrivateKey getPrivateKey(String algo, int keysize) 1336 throws Exception { 1337 KeyFactory kf = KeyFactory.getInstance(algo); 1338 KeySpec kspec; 1339 if (algo.equalsIgnoreCase("DSA")) { 1340 if (keysize == 1024) { 1341 kspec = new DSAPrivateKeySpec 1342 (new BigInteger(DSA_X), new BigInteger(DSA_P), 1343 new BigInteger(DSA_Q), new BigInteger(DSA_G)); 1344 } else if (keysize == 2048) { 1345 kspec = new DSAPrivateKeySpec 1346 (new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P), 1347 new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G)); 1348 } else throw new RuntimeException("Unsupported keysize:" + keysize); 1349 } else if (algo.equalsIgnoreCase("RSA")) { 1350 if (keysize == 512) { 1351 kspec = new RSAPrivateKeySpec 1352 (new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV)); 1353 } else { 1354 kspec = new RSAPrivateKeySpec(new BigInteger(RSA_1024_MOD), 1355 new BigInteger(RSA_1024_PRIV)); 1356 } 1357 } else throw new RuntimeException("Unsupported key algorithm " + algo); 1358 return kf.generatePrivate(kspec); 1359 } 1360 1361 private static PrivateKey getECPrivateKey(String curve) throws Exception { 1362 String s; 1363 ECParameterSpec params; 1364 switch (curve) { 1365 case "P256": 1366 s = EC_P256_S; 1367 params = EC_P256_PARAMS; 1368 break; 1369 case "P384": 1370 s = EC_P384_S; 1371 params = EC_P384_PARAMS; 1372 break; 1373 case "P521": 1374 s = EC_P521_S; 1375 params = EC_P521_PARAMS; 1376 break; 1377 default: 1378 throw new Exception("Unsupported curve: " + curve); 1379 } 1380 KeyFactory kf = KeyFactory.getInstance("EC"); 1381 KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params); 1382 return kf.generatePrivate(kspec); 1383 } 1384 1385 private static SecretKey getSecretKey(final byte[] secret) { 1386 return new SecretKey() { 1387 public String getFormat() { return "RAW"; } 1388 public byte[] getEncoded() { return secret; } 1389 public String getAlgorithm(){ return "SECRET"; } 1390 }; 1391 } 1392 1393 /** 1394 * This URIDereferencer returns locally cached copies of http content to 1395 * avoid test failures due to network glitches, etc. 1396 */ 1397 private static class HttpURIDereferencer implements URIDereferencer { 1398 private URIDereferencer defaultUd; 1399 1400 HttpURIDereferencer() { 1401 defaultUd = XMLSignatureFactory.getInstance().getURIDereferencer(); 1402 } 1403 1404 public Data dereference(final URIReference ref, XMLCryptoContext ctx) 1405 throws URIReferenceException { 1406 String uri = ref.getURI(); 1407 if (uri.equals(STYLESHEET) || uri.equals(STYLESHEET_B64)) { 1408 try { 1409 FileInputStream fis = new FileInputStream(new File 1410 (DATA_DIR, uri.substring(uri.lastIndexOf('/')))); 1411 return new OctetStreamData(fis,ref.getURI(),ref.getType()); 1412 } catch (Exception e) { throw new URIReferenceException(e); } 1413 } 1414 1415 // fallback on builtin deref 1416 return defaultUd.dereference(ref, ctx); 1417 } 1418 } 1419 }