Path: blob/master/test/jdk/javax/xml/crypto/dsig/GenerationTests.java
41152 views
/*1* Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349 804694926* 8046724 8079693 8177334 8205507 8210736 8217878 824130627* @summary Basic unit tests for generating XML Signatures with JSR 10528* @modules java.base/sun.security.util29* java.base/sun.security.x50930* java.xml.crypto/org.jcp.xml.dsig.internal.dom31* jdk.httpserver/com.sun.net.httpserver32* @library /test/lib33* @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java34* X509KeySelector.java GenerationTests.java35* @run main/othervm/timeout=300 -Dsun.net.httpserver.nodelay=true GenerationTests36* @author Sean Mullan37*/3839import com.sun.net.httpserver.HttpExchange;40import com.sun.net.httpserver.HttpHandler;41import com.sun.net.httpserver.HttpServer;42import java.io.*;43import java.lang.reflect.Modifier;44import java.math.BigInteger;45import java.net.InetSocketAddress;46import java.security.Key;47import java.security.KeyFactory;48import java.security.KeyPair;49import java.security.KeyPairGenerator;50import java.security.KeyStore;51import java.security.NoSuchAlgorithmException;52import java.security.PrivateKey;53import java.security.PublicKey;54import java.security.cert.Certificate;55import java.security.cert.CertificateFactory;56import java.security.cert.X509CRL;57import java.security.spec.KeySpec;58import java.security.spec.DSAPrivateKeySpec;59import java.security.spec.DSAPublicKeySpec;60import java.security.spec.ECField;61import java.security.spec.ECFieldFp;62import java.security.spec.ECParameterSpec;63import java.security.spec.ECPoint;64import java.security.spec.ECPrivateKeySpec;65import java.security.spec.ECPublicKeySpec;66import java.security.spec.EllipticCurve;67import java.security.spec.RSAPrivateKeySpec;68import java.security.spec.RSAPublicKeySpec;69import java.util.*;70import java.util.stream.Stream;71import javax.crypto.KeyGenerator;72import javax.crypto.SecretKey;73import javax.xml.XMLConstants;74import javax.xml.parsers.*;75import javax.xml.crypto.Data;76import javax.xml.crypto.KeySelector;77import javax.xml.crypto.OctetStreamData;78import javax.xml.crypto.URIDereferencer;79import javax.xml.crypto.URIReference;80import javax.xml.crypto.URIReferenceException;81import javax.xml.crypto.XMLCryptoContext;82import javax.xml.crypto.XMLStructure;83import javax.xml.crypto.dsig.*;84import javax.xml.crypto.dom.*;85import javax.xml.crypto.dsig.dom.DOMSignContext;86import javax.xml.crypto.dsig.dom.DOMValidateContext;87import javax.xml.crypto.dsig.keyinfo.*;88import javax.xml.crypto.dsig.spec.*;89import javax.xml.transform.*;90import javax.xml.transform.dom.DOMSource;91import javax.xml.transform.stream.StreamResult;92import org.w3c.dom.*;9394import jdk.test.lib.security.SecurityUtils;9596/**97* Test that recreates merlin-xmldsig-twenty-three test vectors (and more)98* but with different keys and X.509 data.99*/100public class GenerationTests {101102private static XMLSignatureFactory fac;103private static KeyInfoFactory kifac;104private static DocumentBuilder db;105private static CanonicalizationMethod withoutComments;106private static SignatureMethod dsaSha1, dsaSha256,107rsaSha1, rsaSha224, rsaSha256, rsaSha384, rsaSha512,108ecdsaSha1, ecdsaSha224, ecdsaSha256, ecdsaSha384, ecdsaSha512,109hmacSha1, hmacSha224, hmacSha256, hmacSha384, hmacSha512,110rsaSha1mgf1, rsaSha224mgf1, rsaSha256mgf1, rsaSha384mgf1, rsaSha512mgf1, rsaShaPSS;111private static DigestMethod sha1, sha224, sha256, sha384, sha512,112sha3_224, sha3_256, sha3_384, sha3_512;113private static KeyInfo dsa1024, dsa2048, rsa, rsa1024, rsa2048,114p256ki, p384ki, p521ki;115private static KeySelector kvks = new KeySelectors.KeyValueKeySelector();116private static KeySelector sks;117private static Key signingKey;118private static PublicKey validatingKey;119private static Certificate signingCert;120private static KeyStore ks;121private final static String DIR = System.getProperty("test.src", ".");122// private final static String DIR = ".";123private final static String DATA_DIR =124DIR + System.getProperty("file.separator") + "data";125private final static String KEYSTORE =126DATA_DIR + System.getProperty("file.separator") + "certs" +127System.getProperty("file.separator") + "test.jks";128private final static String CRL =129DATA_DIR + System.getProperty("file.separator") + "certs" +130System.getProperty("file.separator") + "crl";131// XML Document with a DOCTYPE declaration132private final static String ENVELOPE =133DATA_DIR + System.getProperty("file.separator") + "envelope.xml";134// XML Document without a DOCTYPE declaration135private final static String ENVELOPE2 =136DATA_DIR + System.getProperty("file.separator") + "envelope2.xml";137private static URIDereferencer httpUd = null;138private final static String STYLESHEET =139"http://www.w3.org/TR/xml-stylesheet";140private final static String STYLESHEET_B64 =141"http://www.w3.org/Signature/2002/04/xml-stylesheet.b64";142private final static String DSA_SHA256 =143"http://www.w3.org/2009/xmldsig11#dsa-sha256";144145private static final String BOGUS = "bogus";146147private static final String xslt = ""148+ "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'\n"149+ " xmlns='http://www.w3.org/TR/xhtml1/strict' \n"150+ " exclude-result-prefixes='foo' \n"151+ " version='1.0'>\n"152+ " <xsl:output encoding='UTF-8' \n"153+ " indent='no' \n"154+ " method='xml' />\n"155+ " <xsl:template match='/'>\n"156+ " <html>\n"157+ " <head>\n"158+ " <title>Notaries</title>\n"159+ " </head>\n"160+ " <body>\n"161+ " <table>\n"162+ " <xsl:for-each select='Notaries/Notary'>\n"163+ " <tr>\n"164+ " <th>\n"165+ " <xsl:value-of select='@name' />\n"166+ " </th>\n"167+ " </tr>\n"168+ " </xsl:for-each>\n"169+ " </table>\n"170+ " </body>\n"171+ " </html>\n"172+ " </xsl:template>\n"173+ "</xsl:stylesheet>\n";174175private static final String[] canonicalizationMethods = new String[] {176CanonicalizationMethod.EXCLUSIVE,177CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,178CanonicalizationMethod.INCLUSIVE,179CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS180};181182private static final String[] xml_transforms = new String[] {183Transform.XSLT,184Transform.XPATH,185Transform.XPATH2,186CanonicalizationMethod.EXCLUSIVE,187CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,188CanonicalizationMethod.INCLUSIVE,189CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,190};191192private static final String[] non_xml_transforms = new String[] {193null, Transform.BASE64194};195196// It will be too time consuming to test all combinations of197// all digest methods and signature methods. So we pick some198// majors one and only test a combination when a major method199// (either digest or signature) is included.200//201// * * *202// * * *203// * * *204// * * * * * * * * *205// * * * * * * * * *206// * * * * * * * * *207// * * *208// * * *209// * * *210211private static List<String> majorSignatureMethods = List.of(212SignatureMethod.DSA_SHA256,213SignatureMethod.RSA_SHA256,214SignatureMethod.ECDSA_SHA256,215SignatureMethod.HMAC_SHA256,216SignatureMethod.SHA256_RSA_MGF1,217SignatureMethod.RSA_PSS);218219private static final String[] allSignatureMethods220= Stream.of(SignatureMethod.class.getDeclaredFields())221.filter(f -> Modifier.isStatic(f.getModifiers()))222.map(f -> {223try {224return (String)f.get(null);225} catch (Exception e) {226throw new Error("should not happen");227}228})229.toArray(String[]::new);230231private static final List<String> majorDigestMethods = List.of(232DigestMethod.SHA1,233DigestMethod.SHA256,234DigestMethod.SHA3_256);235236private static final String[] allDigestMethods237= Stream.of(DigestMethod.class.getDeclaredFields())238.filter(f -> Modifier.isStatic(f.getModifiers())239&& !f.getName().equals("RIPEMD160"))240.map(f -> {241try {242return (String)f.get(null);243} catch (Exception e) {244throw new Error("should not happen");245}246})247.toArray(String[]::new);248249// As of JDK 17, the number of defined algorithms are...250static {251if (allSignatureMethods.length != 23252|| allDigestMethods.length != 9) {253System.out.println(Arrays.toString(allSignatureMethods));254System.out.println(Arrays.toString(allDigestMethods));255throw new AssertionError("Not all methods are counted");256}257}258259private static enum Content {260Xml, Text, Base64, NotExisitng261}262263private static enum KeyInfoType {264KeyValue, x509data, KeyName265}266267// cached keys (for performance) used by test_create_detached_signature().268private static HashMap<String,Key[]> cachedKeys = new HashMap<>();269270// Load cachedKeys persisted in a file to reproduce a failure.271// The keys are always saved to "cached-keys" but you can rename272// it to a different file name and load it here. Note: The keys will273// always be persisted so renaming is a good idea although the274// content might not change.275static {276String cacheFile = System.getProperty("use.cached.keys");277if (cacheFile != null) {278try (FileInputStream fis = new FileInputStream(cacheFile);279ObjectInputStream ois = new ObjectInputStream(fis)) {280cachedKeys = (HashMap<String,Key[]>) ois.readObject();281} catch (Exception e) {282throw new AssertionError("Cannot read " + cacheFile, e);283}284}285}286287private static boolean result = true;288289public static void main(String args[]) throws Exception {290// Re-enable sha1 algs291SecurityUtils.removeAlgsFromDSigPolicy("sha1");292293setup();294test_create_signature_enveloped_dsa(1024);295test_create_signature_enveloped_dsa(2048);296test_create_signature_enveloping_b64_dsa();297test_create_signature_enveloping_dsa();298test_create_signature_enveloping_hmac_sha1_40();299test_create_signature_enveloping_hmac_sha256();300test_create_signature_enveloping_hmac_sha224();301test_create_signature_enveloping_hmac_sha384();302test_create_signature_enveloping_hmac_sha512();303test_create_signature_enveloping_rsa();304test_create_signature_enveloping_p256_sha1();305test_create_signature_enveloping_p256_sha224();306test_create_signature_enveloping_p256_sha256();307test_create_signature_enveloping_p256_sha384();308test_create_signature_enveloping_p256_sha512();309test_create_signature_enveloping_p384_sha1();310test_create_signature_enveloping_p521_sha1();311test_create_signature_external_b64_dsa();312test_create_signature_external_dsa();313test_create_signature_keyname();314test_create_signature_retrievalmethod_rawx509crt();315test_create_signature_x509_crt_crl();316test_create_signature_x509_crt();317test_create_signature_x509_is();318test_create_signature_x509_ski();319test_create_signature_x509_sn();320test_create_signature();321test_create_exc_signature();322test_create_sign_spec();323test_create_signature_enveloping_sha256_dsa();324test_create_signature_enveloping_sha384_rsa_sha256();325test_create_signature_enveloping_sha224_rsa_sha256();326test_create_signature_enveloping_sha3_224_rsa_sha256();327test_create_signature_enveloping_sha3_256_rsa_sha256();328test_create_signature_enveloping_sha3_384_rsa_sha256();329test_create_signature_enveloping_sha3_512_rsa_sha256();330test_create_signature_enveloping_sha512_rsa_sha384();331test_create_signature_enveloping_sha512_rsa_sha224();332test_create_signature_enveloping_sha512_rsa_sha512();333test_create_signature_enveloping_sha512_rsa_sha1_mgf1();334test_create_signature_enveloping_sha512_rsa_sha224_mgf1();335test_create_signature_enveloping_sha512_rsa_sha256_mgf1();336test_create_signature_enveloping_sha512_rsa_sha384_mgf1();337test_create_signature_enveloping_sha512_rsa_sha512_mgf1();338test_create_signature_enveloping_sha512_rsa_pss();339test_create_signature_reference_dependency();340test_create_signature_with_attr_in_no_namespace();341test_create_signature_with_empty_id();342test_create_signature_enveloping_over_doc(ENVELOPE, true);343test_create_signature_enveloping_over_doc(ENVELOPE2, true);344test_create_signature_enveloping_over_doc(ENVELOPE, false);345test_create_signature_enveloping_dom_level1();346347// run tests for detached signatures with local http server348try (Http server = Http.startServer()) {349server.start();350351System.out.println("\ntests for XML documents");352Arrays.stream(canonicalizationMethods).forEach(c ->353Arrays.stream(allSignatureMethods).forEach(s ->354Arrays.stream(allDigestMethods).forEach(d ->355Arrays.stream(xml_transforms).forEach(t ->356Arrays.stream(KeyInfoType.values()).forEach(k -> {357if (isMajor(s, d)) {358test_create_detached_signature(c, s, d, t, k,359Content.Xml, server.getPort(), false, null);360}361})))));362363System.out.println("\ntests for text data with no transform");364Arrays.stream(canonicalizationMethods).forEach(c ->365Arrays.stream(allSignatureMethods).forEach(s ->366Arrays.stream(allDigestMethods).forEach(d ->367Arrays.stream(KeyInfoType.values()).forEach(k -> {368if (isMajor(s, d)) {369test_create_detached_signature(c, s, d, null, k,370Content.Text, server.getPort(), false, null);371}372}))));373374System.out.println("\ntests for base64 data");375Arrays.stream(canonicalizationMethods).forEach(c ->376Arrays.stream(allSignatureMethods).forEach(s ->377Arrays.stream(allDigestMethods).forEach(d ->378Arrays.stream(non_xml_transforms).forEach(t ->379Arrays.stream(KeyInfoType.values()).forEach(k -> {380if (isMajor(s, d)) {381test_create_detached_signature(c, s, d, t, k,382Content.Base64, server.getPort(),383false, null);384}385})))));386387// negative tests388389System.out.println("\nunknown CanonicalizationMethod");390test_create_detached_signature(391CanonicalizationMethod.EXCLUSIVE + BOGUS,392SignatureMethod.DSA_SHA1,393DigestMethod.SHA1,394CanonicalizationMethod.INCLUSIVE,395KeyInfoType.KeyName,396Content.Xml,397server.getPort(),398true,399NoSuchAlgorithmException.class);400401System.out.println("\nunknown SignatureMethod");402test_create_detached_signature(403CanonicalizationMethod.EXCLUSIVE,404SignatureMethod.DSA_SHA1 + BOGUS,405DigestMethod.SHA1,406CanonicalizationMethod.INCLUSIVE,407KeyInfoType.KeyName, Content.Xml,408server.getPort(),409true,410NoSuchAlgorithmException.class);411412System.out.println("\nunknown DigestMethod");413test_create_detached_signature(414CanonicalizationMethod.EXCLUSIVE,415SignatureMethod.DSA_SHA1,416DigestMethod.SHA1 + BOGUS,417CanonicalizationMethod.INCLUSIVE,418KeyInfoType.KeyName, Content.Xml,419server.getPort(),420true,421NoSuchAlgorithmException.class);422423System.out.println("\nunknown Transform");424test_create_detached_signature(425CanonicalizationMethod.EXCLUSIVE,426SignatureMethod.DSA_SHA1,427DigestMethod.SHA1,428CanonicalizationMethod.INCLUSIVE + BOGUS,429KeyInfoType.KeyName, Content.Xml,430server.getPort(),431true,432NoSuchAlgorithmException.class);433434System.out.println("\nno source document");435test_create_detached_signature(436CanonicalizationMethod.EXCLUSIVE,437SignatureMethod.DSA_SHA1,438DigestMethod.SHA1,439CanonicalizationMethod.INCLUSIVE,440KeyInfoType.KeyName,441Content.NotExisitng,442server.getPort(),443true,444XMLSignatureException.class);445446System.out.println("\nwrong transform for text data");447test_create_detached_signature(448CanonicalizationMethod.EXCLUSIVE,449SignatureMethod.DSA_SHA1,450DigestMethod.SHA1,451CanonicalizationMethod.INCLUSIVE,452KeyInfoType.KeyName,453Content.Text,454server.getPort(),455true,456XMLSignatureException.class);457}458459// persist cached keys to a file.460try (FileOutputStream fos = new FileOutputStream("cached-keys", true);461ObjectOutputStream oos = new ObjectOutputStream(fos)) {462oos.writeObject(cachedKeys);463}464465if (!result) {466throw new RuntimeException("At least one test case failed");467}468}469470// Do not test on all combinations.471private static boolean isMajor(String signatureMethod, String digestMethod) {472return majorDigestMethods.contains(digestMethod)473|| majorSignatureMethods.contains(signatureMethod);474}475476private static void setup() throws Exception {477fac = XMLSignatureFactory.getInstance();478kifac = fac.getKeyInfoFactory();479DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();480dbf.setNamespaceAware(true);481db = dbf.newDocumentBuilder();482483// get key & self-signed certificate from keystore484FileInputStream fis = new FileInputStream(KEYSTORE);485ks = KeyStore.getInstance("JKS");486ks.load(fis, "changeit".toCharArray());487signingKey = ks.getKey("user", "changeit".toCharArray());488signingCert = ks.getCertificate("user");489validatingKey = signingCert.getPublicKey();490491// create common objects492withoutComments = fac.newCanonicalizationMethod493(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null);494dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null);495dsaSha256 = fac.newSignatureMethod(DSA_SHA256, null);496497sha1 = fac.newDigestMethod(DigestMethod.SHA1, null);498sha224 = fac.newDigestMethod(DigestMethod.SHA224, null);499sha256 = fac.newDigestMethod(DigestMethod.SHA256, null);500sha384 = fac.newDigestMethod(DigestMethod.SHA384, null);501sha512 = fac.newDigestMethod(DigestMethod.SHA512, null);502sha3_224 = fac.newDigestMethod(DigestMethod.SHA3_224, null);503sha3_256 = fac.newDigestMethod(DigestMethod.SHA3_256, null);504sha3_384 = fac.newDigestMethod(DigestMethod.SHA3_384, null);505sha3_512 = fac.newDigestMethod(DigestMethod.SHA3_512, null);506507dsa1024 = kifac.newKeyInfo(Collections.singletonList508(kifac.newKeyValue(validatingKey)));509dsa2048 = kifac.newKeyInfo(Collections.singletonList510(kifac.newKeyValue(getPublicKey("DSA", 2048))));511rsa = kifac.newKeyInfo(Collections.singletonList512(kifac.newKeyValue(getPublicKey("RSA", 512))));513rsa1024 = kifac.newKeyInfo(Collections.singletonList514(kifac.newKeyValue(getPublicKey("RSA", 1024))));515rsa2048 = kifac.newKeyInfo(Collections.singletonList516(kifac.newKeyValue(getPublicKey("RSA", 2048))));517p256ki = kifac.newKeyInfo(Collections.singletonList518(kifac.newKeyValue(getECPublicKey("P256"))));519p384ki = kifac.newKeyInfo(Collections.singletonList520(kifac.newKeyValue(getECPublicKey("P384"))));521p521ki = kifac.newKeyInfo(Collections.singletonList522(kifac.newKeyValue(getECPublicKey("P521"))));523524rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null);525rsaSha224 = fac.newSignatureMethod(SignatureMethod.RSA_SHA224, null);526rsaSha256 = fac.newSignatureMethod(SignatureMethod.RSA_SHA256, null);527rsaSha384 = fac.newSignatureMethod(SignatureMethod.RSA_SHA384, null);528rsaSha512 = fac.newSignatureMethod(SignatureMethod.RSA_SHA512, null);529530rsaSha1mgf1 = fac.newSignatureMethod(SignatureMethod.SHA1_RSA_MGF1, null);531rsaSha224mgf1 = fac.newSignatureMethod(SignatureMethod.SHA224_RSA_MGF1, null);532rsaSha256mgf1 = fac.newSignatureMethod(SignatureMethod.SHA256_RSA_MGF1, null);533rsaSha384mgf1 = fac.newSignatureMethod(SignatureMethod.SHA384_RSA_MGF1, null);534rsaSha512mgf1 = fac.newSignatureMethod(SignatureMethod.SHA512_RSA_MGF1, null);535rsaShaPSS = fac.newSignatureMethod(SignatureMethod. RSA_PSS, null);536537ecdsaSha1 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA1, null);538ecdsaSha224 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA224, null);539ecdsaSha256 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA256, null);540ecdsaSha384 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA384, null);541ecdsaSha512 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA512, null);542543hmacSha1 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA1, null);544hmacSha224 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA224, null);545hmacSha256 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA256, null);546hmacSha384 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA384, null);547hmacSha512 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA512, null);548549sks = new KeySelectors.SecretKeySelector("secret".getBytes("ASCII"));550551httpUd = new HttpURIDereferencer();552}553554static void test_create_signature_enveloped_dsa(int size) throws Exception {555System.out.println("* Generating signature-enveloped-dsa-"556+ size + ".xml");557SignatureMethod sm = null;558KeyInfo ki = null;559Key privKey;560if (size == 1024) {561sm = dsaSha1;562ki = dsa1024;563privKey = signingKey;564} else if (size == 2048) {565sm = dsaSha256;566ki = dsa2048;567privKey = getPrivateKey("DSA", 2048);568} else throw new RuntimeException("unsupported keysize:" + size);569570// create SignedInfo571SignedInfo si = fac.newSignedInfo572(withoutComments, sm, Collections.singletonList573(fac.newReference574("", sha1, Collections.singletonList575(fac.newTransform(Transform.ENVELOPED,576(TransformParameterSpec) null)),577null, null)));578579// create XMLSignature580XMLSignature sig = fac.newXMLSignature(si, ki);581582Document doc = db.newDocument();583Element envelope = doc.createElementNS584("http://example.org/envelope", "Envelope");585envelope.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,586"xmlns", "http://example.org/envelope");587doc.appendChild(envelope);588589DOMSignContext dsc = new DOMSignContext(privKey, envelope);590591sig.sign(dsc);592// StringWriter sw = new StringWriter();593// dumpDocument(doc, sw);594// System.out.println(sw.toString());595596DOMValidateContext dvc = new DOMValidateContext597(kvks, envelope.getFirstChild());598XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);599600if (sig.equals(sig2) == false) {601throw new Exception602("Unmarshalled signature is not equal to generated signature");603}604605if (sig2.validate(dvc) == false) {606throw new Exception("Validation of generated signature failed");607}608System.out.println();609}610611static void test_create_signature_enveloping_b64_dsa() throws Exception {612System.out.println("* Generating signature-enveloping-b64-dsa.xml");613test_create_signature_enveloping614(sha1, dsaSha1, dsa1024, signingKey, kvks, true, true);615System.out.println();616}617618static void test_create_signature_enveloping_dsa() throws Exception {619System.out.println("* Generating signature-enveloping-dsa.xml");620test_create_signature_enveloping621(sha1, dsaSha1, dsa1024, signingKey, kvks, false, true);622System.out.println();623}624625static void test_create_signature_enveloping_sha256_dsa() throws Exception {626System.out.println("* Generating signature-enveloping-sha256-dsa.xml");627test_create_signature_enveloping628(sha256, dsaSha1, dsa1024, signingKey, kvks, false, true);629System.out.println();630}631632static void test_create_signature_enveloping_hmac_sha1_40()633throws Exception {634System.out.println("* Generating signature-enveloping-hmac-sha1-40.xml");635try {636test_create_signature_enveloping(sha1, hmacSha1, null,637getSecretKey("secret".getBytes("ASCII")), sks, false, true);638} catch (Exception e) {639if (!(e instanceof XMLSignatureException)) {640throw e;641}642}643System.out.println();644}645646static void test_create_signature_enveloping_hmac_sha256()647throws Exception {648System.out.println("* Generating signature-enveloping-hmac-sha256.xml");649test_create_signature_enveloping(sha1, hmacSha256, null,650getSecretKey("secret".getBytes("ASCII")), sks, false, true);651System.out.println();652}653654static void test_create_signature_enveloping_hmac_sha224()655throws Exception {656System.out.println("* Generating signature-enveloping-hmac-sha224.xml");657test_create_signature_enveloping(sha1, hmacSha224, null,658getSecretKey("secret".getBytes("ASCII")), sks, false, true);659System.out.println();660}661662static void test_create_signature_enveloping_hmac_sha384()663throws Exception {664System.out.println("* Generating signature-enveloping-hmac-sha384.xml");665test_create_signature_enveloping(sha1, hmacSha384, null,666getSecretKey("secret".getBytes("ASCII")), sks, false, true);667System.out.println();668}669670static void test_create_signature_enveloping_hmac_sha512()671throws Exception {672System.out.println("* Generating signature-enveloping-hmac-sha512.xml");673test_create_signature_enveloping(sha1, hmacSha512, null,674getSecretKey("secret".getBytes("ASCII")), sks, false, true);675System.out.println();676}677678static void test_create_signature_enveloping_rsa() throws Exception {679System.out.println("* Generating signature-enveloping-rsa.xml");680test_create_signature_enveloping(sha1, rsaSha1, rsa,681getPrivateKey("RSA", 512), kvks, false, false);682System.out.println();683}684685static void test_create_signature_enveloping_sha384_rsa_sha256()686throws Exception {687System.out.println("* Generating signature-enveloping-sha384-rsa_sha256.xml");688test_create_signature_enveloping(sha384, rsaSha256, rsa,689getPrivateKey("RSA", 512), kvks, false, false);690System.out.println();691}692693static void test_create_signature_enveloping_sha224_rsa_sha256()694throws Exception {695System.out.println("* Generating signature-enveloping-sha224-rsa_sha256.xml");696test_create_signature_enveloping(sha224, rsaSha256, rsa,697getPrivateKey("RSA", 512), kvks, false, false);698System.out.println();699}700701static void test_create_signature_enveloping_sha3_224_rsa_sha256()702throws Exception {703System.out.println("* Generating signature-enveloping-sha3_224-rsa_sha256.xml");704test_create_signature_enveloping(sha3_224, rsaSha256, rsa,705getPrivateKey("RSA", 512), kvks, false, false);706System.out.println();707}708709static void test_create_signature_enveloping_sha3_256_rsa_sha256()710throws Exception {711System.out.println("* Generating signature-enveloping-sha3_256-rsa_sha256.xml");712test_create_signature_enveloping(sha3_256, rsaSha256, rsa,713getPrivateKey("RSA", 512), kvks, false, false);714System.out.println();715}716717static void test_create_signature_enveloping_sha3_384_rsa_sha256()718throws Exception {719System.out.println("* Generating signature-enveloping-sha3_384-rsa_sha256.xml");720test_create_signature_enveloping(sha3_384, rsaSha256, rsa,721getPrivateKey("RSA", 512), kvks, false, false);722System.out.println();723}724725static void test_create_signature_enveloping_sha3_512_rsa_sha256()726throws Exception {727System.out.println("* Generating signature-enveloping-sha3_512-rsa_sha256.xml");728test_create_signature_enveloping(sha3_512, rsaSha256, rsa,729getPrivateKey("RSA", 512), kvks, false, false);730System.out.println();731}732733static void test_create_signature_enveloping_sha512_rsa_sha384()734throws Exception {735System.out.println("* Generating signature-enveloping-sha512-rsa_sha384.xml");736test_create_signature_enveloping(sha512, rsaSha384, rsa1024,737getPrivateKey("RSA", 1024), kvks, false, true);738System.out.println();739}740741static void test_create_signature_enveloping_sha512_rsa_sha224()742throws Exception {743System.out.println("* Generating signature-enveloping-sha512-rsa_sha224.xml");744test_create_signature_enveloping(sha512, rsaSha224, rsa1024,745getPrivateKey("RSA", 1024), kvks, false, true);746System.out.println();747}748749static void test_create_signature_enveloping_sha512_rsa_sha512()750throws Exception {751System.out.println("* Generating signature-enveloping-sha512-rsa_sha512.xml");752test_create_signature_enveloping(sha512, rsaSha512, rsa1024,753getPrivateKey("RSA", 1024), kvks, false, true);754System.out.println();755}756757static void test_create_signature_enveloping_sha512_rsa_sha1_mgf1()758throws Exception {759System.out.println("* Generating signature-enveloping-sha512-rsa_sha1_mgf1.xml");760test_create_signature_enveloping(sha512, rsaSha1mgf1, rsa1024,761getPrivateKey("RSA", 1024), kvks, false, true);762System.out.println();763}764765static void test_create_signature_enveloping_sha512_rsa_sha224_mgf1()766throws Exception {767System.out.println("* Generating signature-enveloping-sha512-rsa_sha224_mgf1.xml");768test_create_signature_enveloping(sha512, rsaSha224mgf1, rsa1024,769getPrivateKey("RSA", 1024), kvks, false, true);770System.out.println();771}772773static void test_create_signature_enveloping_sha512_rsa_sha256_mgf1()774throws Exception {775System.out.println("* Generating signature-enveloping-sha512-rsa_sha256_mgf1.xml");776test_create_signature_enveloping(sha512, rsaSha256mgf1, rsa1024,777getPrivateKey("RSA", 1024), kvks, false, true);778System.out.println();779}780781static void test_create_signature_enveloping_sha512_rsa_sha384_mgf1()782throws Exception {783System.out.println("* Generating signature-enveloping-sha512-rsa_sha384_mgf1.xml");784test_create_signature_enveloping(sha512, rsaSha384mgf1, rsa1024,785getPrivateKey("RSA", 1024), kvks, false, true);786System.out.println();787}788789static void test_create_signature_enveloping_sha512_rsa_sha512_mgf1()790throws Exception {791System.out.println("* Generating signature-enveloping-sha512-rsa_sha512_mgf1.xml");792test_create_signature_enveloping(sha512, rsaSha512mgf1, rsa2048,793getPrivateKey("RSA", 2048), kvks, false, true);794System.out.println();795}796797static void test_create_signature_enveloping_sha512_rsa_pss()798throws Exception {799System.out.println("* Generating signature-enveloping-sha512_rsa_pss.xml");800test_create_signature_enveloping(sha512, rsaShaPSS, rsa1024,801getPrivateKey("RSA", 1024), kvks, false, true);802System.out.println();803}804805static void test_create_signature_enveloping_p256_sha1() throws Exception {806System.out.println("* Generating signature-enveloping-p256-sha1.xml");807test_create_signature_enveloping(sha1, ecdsaSha1, p256ki,808getECPrivateKey("P256"), kvks, false, true);809System.out.println();810}811812static void test_create_signature_enveloping_p256_sha224() throws Exception {813System.out.println("* Generating signature-enveloping-p256-sha224.xml");814test_create_signature_enveloping(sha1, ecdsaSha224, p256ki,815getECPrivateKey("P256"), kvks, false, true);816System.out.println();817}818819static void test_create_signature_enveloping_p256_sha256() throws Exception {820System.out.println("* Generating signature-enveloping-p256-sha256.xml");821test_create_signature_enveloping(sha1, ecdsaSha256, p256ki,822getECPrivateKey("P256"), kvks, false, true);823System.out.println();824}825826static void test_create_signature_enveloping_p256_sha384() throws Exception {827System.out.println("* Generating signature-enveloping-p256-sha384.xml");828test_create_signature_enveloping(sha1, ecdsaSha384, p256ki,829getECPrivateKey("P256"), kvks, false, true);830System.out.println();831}832833static void test_create_signature_enveloping_p256_sha512() throws Exception {834System.out.println("* Generating signature-enveloping-p256-sha512.xml");835test_create_signature_enveloping(sha1, ecdsaSha512, p256ki,836getECPrivateKey("P256"), kvks, false, true);837System.out.println();838}839840static void test_create_signature_enveloping_p384_sha1() throws Exception {841System.out.println("* Generating signature-enveloping-p384-sha1.xml");842test_create_signature_enveloping(sha1, ecdsaSha1, p384ki,843getECPrivateKey("P384"), kvks, false, true);844System.out.println();845}846847static void test_create_signature_enveloping_p521_sha1() throws Exception {848System.out.println("* Generating signature-enveloping-p521-sha1.xml");849test_create_signature_enveloping(sha1, ecdsaSha1, p521ki,850getECPrivateKey("P521"), kvks, false, true);851System.out.println();852}853854static void test_create_signature_external_b64_dsa() throws Exception {855System.out.println("* Generating signature-external-b64-dsa.xml");856test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, true);857System.out.println();858}859860static void test_create_signature_external_dsa() throws Exception {861System.out.println("* Generating signature-external-dsa.xml");862test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, false);863System.out.println();864}865866static void test_create_signature_keyname() throws Exception {867System.out.println("* Generating signature-keyname.xml");868KeyInfo kn = kifac.newKeyInfo(Collections.singletonList869(kifac.newKeyName("user")));870test_create_signature_external(dsaSha1, kn, signingKey,871new X509KeySelector(ks), false);872System.out.println();873}874875static void test_create_signature_retrievalmethod_rawx509crt()876throws Exception {877System.out.println(878"* Generating signature-retrievalmethod-rawx509crt.xml");879KeyInfo rm = kifac.newKeyInfo(Collections.singletonList880(kifac.newRetrievalMethod881("certs/user.crt", X509Data.RAW_X509_CERTIFICATE_TYPE, null)));882test_create_signature_external(dsaSha1, rm, signingKey,883new X509KeySelector(ks), false);884System.out.println();885}886887static void test_create_signature_x509_crt_crl() throws Exception {888System.out.println("* Generating signature-x509-crt-crl.xml");889List<Object> xds = new ArrayList<>();890CertificateFactory cf = CertificateFactory.getInstance("X.509");891xds.add(signingCert);892FileInputStream fis = new FileInputStream(CRL);893X509CRL crl = (X509CRL) cf.generateCRL(fis);894fis.close();895xds.add(crl);896KeyInfo crt_crl = kifac.newKeyInfo(Collections.singletonList897(kifac.newX509Data(xds)));898899test_create_signature_external(dsaSha1, crt_crl, signingKey,900new X509KeySelector(ks), false);901System.out.println();902}903904static void test_create_signature_x509_crt() throws Exception {905System.out.println("* Generating signature-x509-crt.xml");906KeyInfo crt = kifac.newKeyInfo(Collections.singletonList907(kifac.newX509Data(Collections.singletonList(signingCert))));908909test_create_signature_external(dsaSha1, crt, signingKey,910new X509KeySelector(ks), false);911System.out.println();912}913914static void test_create_signature_x509_is() throws Exception {915System.out.println("* Generating signature-x509-is.xml");916KeyInfo is = kifac.newKeyInfo(Collections.singletonList917(kifac.newX509Data(Collections.singletonList918(kifac.newX509IssuerSerial919("CN=User", new BigInteger("45ef2729", 16))))));920test_create_signature_external(dsaSha1, is, signingKey,921new X509KeySelector(ks), false);922System.out.println();923}924925static void test_create_signature_x509_ski() throws Exception {926System.out.println("* Generating signature-x509-ski.xml");927KeyInfo ski = kifac.newKeyInfo(Collections.singletonList928(kifac.newX509Data(Collections.singletonList929("keyid".getBytes("ASCII")))));930931test_create_signature_external(dsaSha1, ski, signingKey,932KeySelector.singletonKeySelector(validatingKey), false);933System.out.println();934}935936static void test_create_signature_x509_sn() throws Exception {937System.out.println("* Generating signature-x509-sn.xml");938KeyInfo sn = kifac.newKeyInfo(Collections.singletonList939(kifac.newX509Data(Collections.singletonList("CN=User"))));940941test_create_signature_external(dsaSha1, sn, signingKey,942new X509KeySelector(ks), false);943System.out.println();944}945946static void test_create_signature_reference_dependency() throws Exception {947System.out.println("* Generating signature-reference-dependency.xml");948// create references949List<Reference> refs = Collections.singletonList950(fac.newReference("#object-1", sha1));951952// create SignedInfo953SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);954955// create objects956List<XMLObject> objs = new ArrayList<>();957958// Object 1959List<Reference> manRefs = Collections.singletonList960(fac.newReference("#object-2", sha1));961objs.add(fac.newXMLObject(Collections.singletonList962(fac.newManifest(manRefs, "manifest-1")), "object-1", null, null));963964// Object 2965Document doc = db.newDocument();966Element nc = doc.createElementNS(null, "NonCommentandus");967nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");968nc.appendChild(doc.createComment(" Commentandum "));969objs.add(fac.newXMLObject(Collections.singletonList970(new DOMStructure(nc)), "object-2", null, null));971972// create XMLSignature973XMLSignature sig = fac.newXMLSignature(si, rsa, objs, "signature", null);974DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);975976sig.sign(dsc);977978// dumpDocument(doc, new PrintWriter(System.out));979980DOMValidateContext dvc = new DOMValidateContext981(kvks, doc.getDocumentElement());982dvc.setProperty("org.jcp.xml.dsig.secureValidation", false);983XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);984985if (sig.equals(sig2) == false) {986throw new Exception987("Unmarshalled signature is not equal to generated signature");988}989if (sig2.validate(dvc) == false) {990throw new Exception("Validation of generated signature failed");991}992993System.out.println();994}995996static void test_create_signature_with_attr_in_no_namespace()997throws Exception998{999System.out.println1000("* Generating signature-with-attr-in-no-namespace.xml");10011002// create references1003List<Reference> refs = Collections.singletonList1004(fac.newReference("#unknown", sha1));10051006// create SignedInfo1007SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);10081009// create object-11010Document doc = db.newDocument();1011Element nc = doc.createElementNS(null, "NonCommentandus");1012// add attribute with no namespace1013nc.setAttribute("Id", "unknown");1014XMLObject obj = fac.newXMLObject(Collections.singletonList1015(new DOMStructure(nc)), "object-1", null, null);10161017// create XMLSignature1018XMLSignature sig = fac.newXMLSignature(si, rsa,1019Collections.singletonList(obj),1020"signature", null);1021DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);1022dsc.setIdAttributeNS(nc, null, "Id");10231024sig.sign(dsc);10251026// dumpDocument(doc, new PrintWriter(System.out));10271028DOMValidateContext dvc = new DOMValidateContext1029(kvks, doc.getDocumentElement());1030dvc.setProperty("org.jcp.xml.dsig.secureValidation", false);1031dvc.setIdAttributeNS(nc, null, "Id");1032XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);10331034if (sig.equals(sig2) == false) {1035throw new Exception1036("Unmarshalled signature is not equal to generated signature");1037}1038if (sig2.validate(dvc) == false) {1039throw new Exception("Validation of generated signature failed");1040}10411042System.out.println();1043}10441045static void test_create_signature_with_empty_id() throws Exception {1046System.out.println("* Generating signature-with-empty-id.xml");10471048// create references1049List<Reference> refs = Collections.singletonList1050(fac.newReference("#", sha1));10511052// create SignedInfo1053SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);10541055// create object with empty id1056Document doc = db.newDocument();1057XMLObject obj = fac.newXMLObject(Collections.singletonList1058(new DOMStructure(doc.createTextNode("I am the text."))),1059"", "text/plain", null);10601061// create XMLSignature1062XMLSignature sig = fac.newXMLSignature(si, rsa,1063Collections.singletonList(obj),1064"signature", null);1065DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);1066sig.sign(dsc);10671068System.out.println();1069}10701071static void test_create_signature_enveloping_over_doc(String filename,1072boolean pass) throws Exception1073{1074System.out.println("* Generating signature-enveloping-over-doc.xml");10751076// create reference1077Reference ref = fac.newReference("#object", sha256);10781079// create SignedInfo1080SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha256,1081Collections.singletonList(ref));10821083// create object1084Document doc = null;1085try (FileInputStream fis = new FileInputStream(filename)) {1086doc = db.parse(fis);1087}1088DOMStructure ds = pass ? new DOMStructure(doc.getDocumentElement())1089: new DOMStructure(doc);1090XMLObject obj = fac.newXMLObject(Collections.singletonList(ds),1091"object", null, "UTF-8");10921093// This creates an enveloping signature over the entire XML Document1094XMLSignature sig = fac.newXMLSignature(si, rsa,1095Collections.singletonList(obj),1096"signature", null);1097DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 1024), doc);1098try {1099sig.sign(dsc);1100if (!pass) {1101// A Document node can only exist at the root of the doc so this1102// should fail1103throw new Exception("Test unexpectedly passed");1104}1105} catch (Exception e) {1106if (!pass) {1107System.out.println("Test failed as expected: " + e);1108} else {1109throw e;1110}1111}11121113if (pass) {1114DOMValidateContext dvc = new DOMValidateContext1115(getPublicKey("RSA", 1024), doc.getDocumentElement());1116XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);11171118if (sig.equals(sig2) == false) {1119throw new Exception1120("Unmarshalled signature is not equal to generated signature");1121}1122if (sig2.validate(dvc) == false) {1123throw new Exception("Validation of generated signature failed");1124}1125}11261127System.out.println();1128}11291130static void test_create_signature_enveloping_dom_level1() throws Exception {1131System.out.println("* Generating signature-enveloping-dom-level1.xml");11321133// create reference1134Reference ref = fac.newReference("#object", sha256);11351136// create SignedInfo1137SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha256,1138Collections.singletonList(ref));11391140// create object using DOM Level 1 methods1141Document doc = db.newDocument();1142Element child = doc.createElement("Child");1143child.setAttribute("Version", "1.0");1144child.setAttribute("Id", "child");1145child.setIdAttribute("Id", true);1146child.appendChild(doc.createComment("Comment"));1147XMLObject obj = fac.newXMLObject(1148Collections.singletonList(new DOMStructure(child)),1149"object", null, "UTF-8");11501151XMLSignature sig = fac.newXMLSignature(si, rsa,1152Collections.singletonList(obj),1153"signature", null);1154DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 1024), doc);1155sig.sign(dsc);11561157DOMValidateContext dvc = new DOMValidateContext1158(getPublicKey("RSA", 1024), doc.getDocumentElement());1159XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);11601161if (sig.equals(sig2) == false) {1162throw new Exception1163("Unmarshalled signature is not equal to generated signature");1164}1165if (sig2.validate(dvc) == false) {1166throw new Exception("Validation of generated signature failed");1167}11681169System.out.println();1170}11711172static void test_create_signature() throws Exception {1173System.out.println("* Generating signature.xml");11741175// create references1176List<Reference> refs = new ArrayList<>();11771178// Reference 11179refs.add(fac.newReference(STYLESHEET, sha1));11801181// Reference 21182refs.add(fac.newReference1183(STYLESHEET_B64,1184sha1, Collections.singletonList1185(fac.newTransform(Transform.BASE64,1186(TransformParameterSpec) null)), null, null));11871188// Reference 31189refs.add(fac.newReference("#object-1", sha1, Collections.singletonList1190(fac.newTransform(Transform.XPATH,1191new XPathFilterParameterSpec("self::text()"))),1192XMLObject.TYPE, null));11931194// Reference 41195String expr = "\n"1196+ " ancestor-or-self::dsig:SignedInfo " + "\n"1197+ " and " + "\n"1198+ " count(ancestor-or-self::dsig:Reference | " + "\n"1199+ " here()/ancestor::dsig:Reference[1]) > " + "\n"1200+ " count(ancestor-or-self::dsig:Reference) " + "\n"1201+ " or " + "\n"1202+ " count(ancestor-or-self::node() | " + "\n"1203+ " id('notaries')) = " + "\n"1204+ " count(ancestor-or-self::node()) " + "\n";12051206XPathFilterParameterSpec xfp = new XPathFilterParameterSpec(expr,1207Collections.singletonMap("dsig", XMLSignature.XMLNS));1208refs.add(fac.newReference("", sha1, Collections.singletonList1209(fac.newTransform(Transform.XPATH, xfp)),1210XMLObject.TYPE, null));12111212// Reference 51213refs.add(fac.newReference("#object-2", sha1, Collections.singletonList1214(fac.newTransform1215(Transform.BASE64, (TransformParameterSpec) null)),1216XMLObject.TYPE, null));12171218// Reference 61219refs.add(fac.newReference1220("#manifest-1", sha1, null, Manifest.TYPE, null));12211222// Reference 71223refs.add(fac.newReference("#signature-properties-1", sha1, null,1224SignatureProperties.TYPE, null));12251226// Reference 81227List<Transform> transforms = new ArrayList<>();1228transforms.add(fac.newTransform1229(Transform.ENVELOPED, (TransformParameterSpec) null));1230refs.add(fac.newReference("", sha1, transforms, null, null));12311232// Reference 91233transforms.add(fac.newTransform1234(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,1235(TransformParameterSpec) null));1236refs.add(fac.newReference("", sha1, transforms, null, null));12371238// Reference 101239Transform env = fac.newTransform1240(Transform.ENVELOPED, (TransformParameterSpec) null);1241refs.add(fac.newReference("#xpointer(/)",1242sha1, Collections.singletonList(env), null, null));12431244// Reference 111245transforms.clear();1246transforms.add(fac.newTransform1247(Transform.ENVELOPED, (TransformParameterSpec) null));1248transforms.add(fac.newTransform1249(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,1250(TransformParameterSpec) null));1251refs.add(fac.newReference("#xpointer(/)", sha1, transforms,1252null, null));12531254// Reference 121255refs.add1256(fac.newReference("#object-3", sha1, null, XMLObject.TYPE, null));12571258// Reference 131259Transform withComments = fac.newTransform1260(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,1261(TransformParameterSpec) null);1262refs.add(fac.newReference("#object-3", sha1,1263Collections.singletonList(withComments), XMLObject.TYPE, null));12641265// Reference 141266refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, null,1267XMLObject.TYPE, null));12681269// Reference 151270withComments = fac.newTransform1271(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,1272(TransformParameterSpec) null);1273refs.add(fac.newReference("#xpointer(id('object-3'))", sha1,1274Collections.singletonList(withComments), XMLObject.TYPE, null));12751276// Reference 161277refs.add(fac.newReference("#reference-2", sha1));12781279// Reference 171280refs.add(fac.newReference("#manifest-reference-1", sha1, null,1281null, "reference-1"));12821283// Reference 181284refs.add(fac.newReference("#reference-1", sha1, null, null,1285"reference-2"));12861287// create SignedInfo1288SignedInfo si = fac.newSignedInfo(withoutComments, dsaSha1, refs);12891290// create keyinfo1291XPathFilterParameterSpec xpf = new XPathFilterParameterSpec(1292"ancestor-or-self::dsig:X509Data",1293Collections.singletonMap("dsig", XMLSignature.XMLNS));1294RetrievalMethod rm = kifac.newRetrievalMethod("#object-4",1295X509Data.TYPE, Collections.singletonList(fac.newTransform1296(Transform.XPATH, xpf)));1297KeyInfo ki = kifac.newKeyInfo(Collections.singletonList(rm), null);12981299Document doc = db.newDocument();13001301// create objects1302List<XMLObject> objs = new ArrayList<>();13031304// Object 11305objs.add(fac.newXMLObject(Collections.singletonList1306(new DOMStructure(doc.createTextNode("I am the text."))),1307"object-1", "text/plain", null));13081309// Object 21310objs.add(fac.newXMLObject(Collections.singletonList1311(new DOMStructure(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="))),1312"object-2", "text/plain", Transform.BASE64));13131314// Object 31315Element nc = doc.createElementNS(null, "NonCommentandus");1316nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");1317nc.appendChild(doc.createComment(" Commentandum "));1318objs.add(fac.newXMLObject(Collections.singletonList1319(new DOMStructure(nc)), "object-3", null, null));13201321// Manifest1322List<Reference> manRefs = new ArrayList<>();13231324// Manifest Reference 11325manRefs.add(fac.newReference(STYLESHEET,1326sha1, null, null, "manifest-reference-1"));13271328// Manifest Reference 21329manRefs.add(fac.newReference("#reference-1", sha1));13301331// Manifest Reference 31332List<Transform> manTrans = new ArrayList<>();1333Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));1334Node xslElem = docxslt.getDocumentElement();13351336manTrans.add(fac.newTransform(Transform.XSLT,1337new XSLTTransformParameterSpec(new DOMStructure(xslElem))));1338manTrans.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE,1339(TransformParameterSpec) null));1340manRefs.add(fac.newReference("#notaries", sha1, manTrans, null, null));13411342objs.add(fac.newXMLObject(Collections.singletonList1343(fac.newManifest(manRefs, "manifest-1")), null, null, null));13441345// SignatureProperties1346Element sa = doc.createElementNS("urn:demo", "SignerAddress");1347sa.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:demo");1348Element ip = doc.createElementNS("urn:demo", "IP");1349ip.appendChild(doc.createTextNode("192.168.21.138"));1350sa.appendChild(ip);1351SignatureProperty sp = fac.newSignatureProperty1352(Collections.singletonList(new DOMStructure(sa)),1353"#signature", null);1354SignatureProperties sps = fac.newSignatureProperties1355(Collections.singletonList(sp), "signature-properties-1");1356objs.add(fac.newXMLObject(Collections.singletonList(sps), null,1357null, null));13581359// Object 41360List<Object> xds = new ArrayList<>();1361xds.add("CN=User");1362xds.add(kifac.newX509IssuerSerial1363("CN=User", new BigInteger("45ef2729", 16)));1364xds.add(signingCert);1365objs.add(fac.newXMLObject(Collections.singletonList1366(kifac.newX509Data(xds)), "object-4", null, null));13671368// create XMLSignature1369XMLSignature sig = fac.newXMLSignature(si, ki, objs, "signature", null);13701371DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();1372dbf.setNamespaceAware(true);1373dbf.setValidating(false);1374Document envDoc = dbf.newDocumentBuilder().parse1375(new FileInputStream(ENVELOPE));1376Element ys = (Element)1377envDoc.getElementsByTagName("YoursSincerely").item(0);13781379DOMSignContext dsc = new DOMSignContext(signingKey, ys);1380dsc.setURIDereferencer(httpUd);13811382sig.sign(dsc);13831384// StringWriter sw = new StringWriter();1385// dumpDocument(envDoc, sw);13861387NodeList nl =1388envDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");1389if (nl.getLength() == 0) {1390throw new Exception("Couldn't find signature Element");1391}1392Element sigElement = (Element) nl.item(0);13931394DOMValidateContext dvc = new DOMValidateContext1395(new X509KeySelector(ks), sigElement);1396dvc.setURIDereferencer(httpUd);1397File f = new File(1398System.getProperty("dir.test.vector.baltimore") +1399System.getProperty("file.separator") +1400"merlin-xmldsig-twenty-three" +1401System.getProperty("file.separator"));1402dvc.setBaseURI(f.toURI().toString());14031404XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);14051406if (sig.equals(sig2) == false) {1407throw new Exception1408("Unmarshalled signature is not equal to generated signature");1409}1410if (sig2.validate(dvc) == false) {1411throw new Exception("Validation of generated signature failed");1412}1413System.out.println();1414}14151416private static void dumpDocument(Document doc, Writer w) throws Exception {1417TransformerFactory tf = TransformerFactory.newInstance();1418Transformer trans = tf.newTransformer();1419// trans.setOutputProperty(OutputKeys.INDENT, "yes");1420trans.transform(new DOMSource(doc), new StreamResult(w));1421}14221423private static void test_create_signature_external1424(SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks,1425boolean b64) throws Exception {14261427// create reference1428Reference ref;1429if (b64) {1430ref = fac.newReference1431(STYLESHEET_B64,1432sha1, Collections.singletonList1433(fac.newTransform(Transform.BASE64,1434(TransformParameterSpec) null)), null, null);1435} else {1436ref = fac.newReference(STYLESHEET, sha1);1437}14381439// create SignedInfo1440SignedInfo si = fac.newSignedInfo(withoutComments, sm,1441Collections.singletonList(ref));14421443Document doc = db.newDocument();14441445// create XMLSignature1446XMLSignature sig = fac.newXMLSignature(si, ki);14471448DOMSignContext dsc = new DOMSignContext(signingKey, doc);1449dsc.setURIDereferencer(httpUd);14501451sig.sign(dsc);14521453DOMValidateContext dvc = new DOMValidateContext1454(ks, doc.getDocumentElement());1455File f = new File(DATA_DIR);1456dvc.setBaseURI(f.toURI().toString());1457dvc.setURIDereferencer(httpUd);14581459XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);14601461if (sig.equals(sig2) == false) {1462throw new Exception1463("Unmarshalled signature is not equal to generated signature");1464}1465if (sig2.validate(dvc) == false) {1466throw new Exception("Validation of generated signature failed");1467}1468}14691470private static void test_create_signature_enveloping1471(DigestMethod dm, SignatureMethod sm, KeyInfo ki, Key signingKey,1472KeySelector ks, boolean b64, boolean secVal) throws Exception {14731474// create reference1475Reference ref;1476if (b64) {1477ref = fac.newReference("#object", dm, Collections.singletonList1478(fac.newTransform(Transform.BASE64,1479(TransformParameterSpec) null)), null, null);1480} else {1481ref = fac.newReference("#object", dm);1482}14831484// create SignedInfo1485SignedInfo si = fac.newSignedInfo(withoutComments, sm,1486Collections.singletonList(ref));14871488Document doc = db.newDocument();1489// create Objects1490String text = b64 ? "c29tZSB0ZXh0" : "some text";1491XMLObject obj = fac.newXMLObject(Collections.singletonList1492(new DOMStructure(doc.createTextNode(text))),1493"object", null, null);14941495// create XMLSignature1496XMLSignature sig = fac.newXMLSignature1497(si, ki, Collections.singletonList(obj), null, null);14981499DOMSignContext dsc = new DOMSignContext(signingKey, doc);15001501sig.sign(dsc);15021503// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));15041505DOMValidateContext dvc = new DOMValidateContext1506(ks, doc.getDocumentElement());1507dvc.setProperty("org.jcp.xml.dsig.secureValidation", secVal);1508XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);15091510if (sig.equals(sig2) == false) {1511throw new Exception1512("Unmarshalled signature is not equal to generated signature");1513}1514if (sig2.validate(dvc) == false) {1515throw new Exception("Validation of generated signature failed");1516}1517}15181519static void test_create_exc_signature() throws Exception {1520System.out.println("* Generating exc_signature.xml");1521List<Reference> refs = new ArrayList<>(4);15221523// create reference 11524refs.add(fac.newReference1525("#xpointer(id('to-be-signed'))", sha1,1526Collections.singletonList1527(fac.newTransform(CanonicalizationMethod.EXCLUSIVE,1528(TransformParameterSpec) null)),1529null, null));15301531// create reference 21532List<String> prefixList = new ArrayList<>(2);1533prefixList.add("bar");1534prefixList.add("#default");1535ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);1536refs.add(fac.newReference1537("#xpointer(id('to-be-signed'))", sha1,1538Collections.singletonList1539(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)),1540null, null));15411542// create reference 31543refs.add(fac.newReference1544("#xpointer(id('to-be-signed'))", sha1,1545Collections.singletonList(fac.newTransform1546(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,1547(TransformParameterSpec) null)),1548null, null));15491550// create reference 41551prefixList = new ArrayList<>(2);1552prefixList.add("bar");1553prefixList.add("#default");1554params = new ExcC14NParameterSpec(prefixList);1555refs.add(fac.newReference1556("#xpointer(id('to-be-signed'))", sha1,1557Collections.singletonList(fac.newTransform1558(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)),1559null, null));15601561// create SignedInfo1562SignedInfo si = fac.newSignedInfo(1563fac.newCanonicalizationMethod1564(CanonicalizationMethod.EXCLUSIVE,1565(C14NMethodParameterSpec) null),1566dsaSha1, refs);15671568// create KeyInfo1569List<XMLStructure> kits = new ArrayList<>(2);1570kits.add(kifac.newKeyValue(validatingKey));1571KeyInfo ki = kifac.newKeyInfo(kits);15721573// create Objects1574Document doc = db.newDocument();1575Element baz = doc.createElementNS("urn:bar", "bar:Baz");1576Comment com = doc.createComment(" comment ");1577baz.appendChild(com);1578XMLObject obj = fac.newXMLObject(Collections.singletonList1579(new DOMStructure(baz)), "to-be-signed", null, null);15801581// create XMLSignature1582XMLSignature sig = fac.newXMLSignature1583(si, ki, Collections.singletonList(obj), null, null);15841585Element foo = doc.createElementNS("urn:foo", "Foo");1586foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");1587foo.setAttributeNS1588("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");1589doc.appendChild(foo);15901591DOMSignContext dsc = new DOMSignContext(signingKey, foo);1592dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");15931594sig.sign(dsc);15951596// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));15971598DOMValidateContext dvc = new DOMValidateContext1599(new KeySelectors.KeyValueKeySelector(), foo.getLastChild());1600XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);16011602if (sig.equals(sig2) == false) {1603throw new Exception1604("Unmarshalled signature is not equal to generated signature");1605}1606if (sig2.validate(dvc) == false) {1607throw new Exception("Validation of generated signature failed");1608}1609System.out.println();1610}16111612static void test_create_sign_spec() throws Exception {1613System.out.println("* Generating sign-spec.xml");1614List<Reference> refs = new ArrayList<>(2);16151616// create reference 11617List<XPathType> types = new ArrayList<>(3);1618types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT));1619types.add(new XPathType(" //NotToBeSigned ",1620XPathType.Filter.SUBTRACT));1621types.add(new XPathType(" //ReallyToBeSigned ",1622XPathType.Filter.UNION));1623XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);1624refs.add(fac.newReference("", sha1,1625Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)),1626null, null));16271628// create reference 21629List<Transform> trans2 = new ArrayList<>(2);1630trans2.add(fac.newTransform(Transform.ENVELOPED,1631(TransformParameterSpec) null));1632XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec1633(Collections.singletonList1634(new XPathType(" / ", XPathType.Filter.UNION)));1635trans2.add(fac.newTransform(Transform.XPATH2, xp2));1636refs.add(fac.newReference("#signature-value", sha1, trans2, null, null));16371638// create SignedInfo1639SignedInfo si = fac.newSignedInfo(1640fac.newCanonicalizationMethod1641(CanonicalizationMethod.INCLUSIVE,1642(C14NMethodParameterSpec) null),1643dsaSha1, refs);16441645// create KeyInfo1646List<XMLStructure> kits = new ArrayList<>(2);1647kits.add(kifac.newKeyValue(validatingKey));1648List<Object> xds = new ArrayList<>(2);1649xds.add("CN=User");1650xds.add(signingCert);1651kits.add(kifac.newX509Data(xds));1652KeyInfo ki = kifac.newKeyInfo(kits);16531654// create XMLSignature1655XMLSignature sig = fac.newXMLSignature1656(si, ki, null, null, "signature-value");16571658Document doc = db.newDocument();1659Element tbs1 = doc.createElementNS(null, "ToBeSigned");1660Comment tbs1Com = doc.createComment(" comment ");1661Element tbs1Data = doc.createElementNS(null, "Data");1662Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned");1663Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned");1664Comment tbs1rtbsCom = doc.createComment(" comment ");1665Element tbs1rtbsData = doc.createElementNS(null, "Data");1666tbs1rtbs.appendChild(tbs1rtbsCom);1667tbs1rtbs.appendChild(tbs1rtbsData);1668tbs1ntbs.appendChild(tbs1rtbs);1669tbs1.appendChild(tbs1Com);1670tbs1.appendChild(tbs1Data);1671tbs1.appendChild(tbs1ntbs);16721673Element tbs2 = doc.createElementNS(null, "ToBeSigned");1674Element tbs2Data = doc.createElementNS(null, "Data");1675Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned");1676Element tbs2ntbsData = doc.createElementNS(null, "Data");1677tbs2ntbs.appendChild(tbs2ntbsData);1678tbs2.appendChild(tbs2Data);1679tbs2.appendChild(tbs2ntbs);16801681Element document = doc.createElementNS(null, "Document");1682document.appendChild(tbs1);1683document.appendChild(tbs2);1684doc.appendChild(document);16851686DOMSignContext dsc = new DOMSignContext(signingKey, document);16871688sig.sign(dsc);16891690// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));16911692DOMValidateContext dvc = new DOMValidateContext1693(new KeySelectors.KeyValueKeySelector(), document.getLastChild());1694XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);16951696if (sig.equals(sig2) == false) {1697throw new Exception1698("Unmarshalled signature is not equal to generated signature");1699}1700if (sig2.validate(dvc) == false) {1701throw new Exception("Validation of generated signature failed");1702}1703System.out.println();1704}17051706// Only print if there is an error.1707static void test_create_detached_signature(1708String canonicalizationMethod, String signatureMethod,1709String digestMethod, String transform, KeyInfoType keyInfo,1710Content contentType, int port, boolean expectedFailure,1711Class expectedException) {17121713String title = "\nTest detached signature:"1714+ "\n Canonicalization method: " + canonicalizationMethod1715+ "\n Signature method: " + signatureMethod1716+ "\n Transform: " + transform1717+ "\n Digest method: " + digestMethod1718+ "\n KeyInfoType: " + keyInfo1719+ "\n Content type: " + contentType1720+ "\n Expected failure: " + (expectedFailure ? "yes" : "no")1721+ "\n Expected exception: " + (expectedException == null ?1722"no" : expectedException.getName());17231724try {1725boolean success = test_create_detached_signature0(1726canonicalizationMethod,1727signatureMethod,1728digestMethod,1729transform,1730keyInfo,1731contentType,1732port);17331734if (success && expectedFailure) {1735System.out.println(title);1736System.out.println("Signature validation unexpectedly passed");1737result = false;1738} else if (!success && !expectedFailure) {1739System.out.println(title);1740System.out.println("Signature validation unexpectedly failed");1741result = false;1742} else if (expectedException != null) {1743System.out.println(title);1744System.out.println("Expected " + expectedException1745+ " not thrown");1746result = false;1747}1748} catch (Exception e) {1749if (expectedException == null1750|| !e.getClass().isAssignableFrom(expectedException)) {1751System.out.println(title);1752System.out.println("Unexpected exception: " + e);1753e.printStackTrace(System.out);1754result = false;1755}1756}1757}17581759// Print out as little as possible. This method will be called many times.1760static boolean test_create_detached_signature0(String canonicalizationMethod,1761String signatureMethod, String digestMethod, String transform,1762KeyInfoType keyInfo, Content contentType, int port)1763throws Exception {17641765System.out.print("-S");1766System.out.flush();17671768DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();1769dbf.setNamespaceAware(true);1770dbf.setValidating(false);17711772// Create SignedInfo1773DigestMethod dm = fac.newDigestMethod(digestMethod, null);17741775List transformList = null;1776if (transform != null) {1777TransformParameterSpec params = null;1778switch (transform) {1779case Transform.XPATH:1780params = new XPathFilterParameterSpec("//.");1781break;1782case Transform.XPATH2:1783params = new XPathFilter2ParameterSpec(1784Collections.singletonList(new XPathType("//.",1785XPathType.Filter.INTERSECT)));1786break;1787case Transform.XSLT:1788Element element = dbf.newDocumentBuilder()1789.parse(new ByteArrayInputStream(xslt.getBytes()))1790.getDocumentElement();1791DOMStructure stylesheet = new DOMStructure(element);1792params = new XSLTTransformParameterSpec(stylesheet);1793break;1794}1795transformList = Collections.singletonList(fac.newTransform(1796transform, params));1797}17981799String url = String.format("http://localhost:%d/%s", port, contentType);1800List refs = Collections.singletonList(fac.newReference(url, dm,1801transformList, null, null));18021803CanonicalizationMethod cm = fac.newCanonicalizationMethod(1804canonicalizationMethod, (C14NMethodParameterSpec) null);18051806SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);18071808Key[] pair = getCachedKeys(signatureMethod);1809Key signingKey = pair[0];1810Key validationKey = pair[1];18111812SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);18131814// Create KeyInfo1815KeyInfoFactory kif = fac.getKeyInfoFactory();1816List list = null;1817if (keyInfo == KeyInfoType.KeyValue) {1818if (validationKey instanceof PublicKey) {1819KeyValue kv = kif.newKeyValue((PublicKey) validationKey);1820list = Collections.singletonList(kv);1821}1822} else if (keyInfo == KeyInfoType.x509data) {1823list = Collections.singletonList(1824kif.newX509Data(Collections.singletonList("cn=Test")));1825} else if (keyInfo == KeyInfoType.KeyName) {1826list = Collections.singletonList(kif.newKeyName("Test"));1827} else {1828throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);1829}1830KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;18311832// Create an empty doc for detached signature1833Document doc = dbf.newDocumentBuilder().newDocument();1834DOMSignContext xsc = new DOMSignContext(signingKey, doc);18351836// Generate signature1837XMLSignature signature = fac.newXMLSignature(si, ki);1838signature.sign(xsc);18391840// Save signature1841String signatureString;1842try (StringWriter writer = new StringWriter()) {1843TransformerFactory tf = TransformerFactory.newInstance();1844Transformer trans = tf.newTransformer();1845Node parent = xsc.getParent();1846trans.transform(new DOMSource(parent), new StreamResult(writer));1847signatureString = writer.toString();1848}18491850System.out.print("V");1851System.out.flush();1852try (ByteArrayInputStream bis = new ByteArrayInputStream(1853signatureString.getBytes())) {1854doc = dbf.newDocumentBuilder().parse(bis);1855}18561857NodeList nodeLst = doc.getElementsByTagName("Signature");1858Node node = nodeLst.item(0);1859if (node == null) {1860throw new RuntimeException("Couldn't find Signature element");1861}1862if (!(node instanceof Element)) {1863throw new RuntimeException("Unexpected node type");1864}1865Element sig = (Element) node;18661867// Validate signature1868DOMValidateContext vc = new DOMValidateContext(validationKey, sig);1869vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);1870signature = fac.unmarshalXMLSignature(vc);18711872boolean success = signature.validate(vc);1873if (!success) {1874System.out.print("x");1875System.out.flush();1876return false;1877}18781879success = signature.getSignatureValue().validate(vc);1880if (!success) {1881System.out.print("X");1882System.out.flush();1883return false;1884}18851886return true;1887}18881889private static Key[] getCachedKeys(String signatureMethod) {1890return cachedKeys.computeIfAbsent(signatureMethod, sm -> {1891try {1892System.out.print("<create keys for " + sm + ">");1893System.out.flush();1894if (sm.contains("#hmac-")) {1895// http://...#hmac-sha1 -> hmac-sha1 -> hmacsha11896String algName = sm1897.substring(sm.indexOf('#') + 1)1898.replace("-", "");1899KeyGenerator kg = KeyGenerator.getInstance(algName);1900Key signingKey = kg.generateKey();1901return new Key[] { signingKey, signingKey};1902} else {1903KeyPairGenerator kpg;1904if (sm.contains("#rsa-")1905|| sm.contains("-rsa-MGF1")) {1906kpg = KeyPairGenerator.getInstance("RSA");1907kpg.initialize(1908sm.contains("#sha512-rsa-MGF1") ? 2048 : 1024);1909} else if (sm.contains("#dsa-")) {1910kpg = KeyPairGenerator.getInstance("DSA");1911kpg.initialize(1024);1912} else if (sm.contains("#ecdsa-")) {1913kpg = KeyPairGenerator.getInstance("EC");1914kpg.initialize(256);1915} else {1916throw new RuntimeException("Unsupported signature algorithm");1917}1918KeyPair kp = kpg.generateKeyPair();1919return new Key[] { kp.getPrivate(), kp.getPublic()};1920}1921} catch (NoSuchAlgorithmException e) {1922throw new AssertionError("Should not happen", e);1923}1924});1925}19261927private static final String DSA_Y =1928"070662842167565771936588335128634396171789331656318483584455493822" +1929"400811200853331373030669235424928346190274044631949560438023934623" +1930"71310375123430985057160";1931private static final String DSA_P =1932"013232376895198612407547930718267435757728527029623408872245156039" +1933"757713029036368719146452186041204237350521785240337048752071462798" +1934"273003935646236777459223";1935private static final String DSA_Q =1936"0857393771208094202104259627990318636601332086981";1937private static final String DSA_G =1938"054216440574364751416096484883257051280474283943804743768346673007" +1939"661082626139005426812890807137245973106730741193551360857959820973" +1940"90670890367185141189796";1941private static final String DSA_X =1942"0527140396812450214498055937934275626078768840117";1943private static final String DSA_2048_Y =1944"15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928";1945private static final String DSA_2048_P =1946"18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359";1947private static final String DSA_2048_Q =1948"19689526866605154788513693571065914024068069442724893395618704484701";1949private static final String DSA_2048_G =1950"2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430";1951private static final String DSA_2048_X =1952"14562787764977288900757387442281559936279834964901963465277698843172";1953private static final String RSA_MOD =1954"010800185049102889923150759252557522305032794699952150943573164381" +1955"936603255999071981574575044810461362008102247767482738822150129277" +1956"490998033971789476107463";1957private static final String RSA_PRIV =1958"016116973584421969795445996229612671947635798429212816611707210835" +1959"915586591340598683996088487065438751488342251960069575392056288063" +1960"6800379454345804879553";1961private static final String RSA_PUB = "065537";1962private static final String RSA_1024_MOD = "098871307553789439961130765" +1963"909423744508062468450669519128736624058048856940468016843888594585" +1964"322862378444314635412341974900625010364163960238734457710620107530" +1965"573945081856371709138380902553309075505688814637544923038853658690" +1966"857672483016239697038853418682988686871489963827000080098971762923" +1967"833614557257607521";1968private static final String RSA_1024_PRIV = "03682574144968491431483287" +1969"297021581096848810374110568017963075809477047466189822987258068867" +1970"704855380407747867998863645890602646601140183818953428006646987710" +1971"237008997971129772408397621801631622129297063463868593083106979716" +1972"204903524890556839550490384015324575598723478554854070823335021842" +1973"210112348400928769";1974private static final String RSA_2048_MOD = "243987087691547796017401146540"1975+ "9844666035826535295137885613771811531602666348704672255163984907599"1976+ "4298308997053582963763109207465354916871136820987101812436158377530"1977+ "6117270010853232249007544652859474372258057062943608962079402484091"1978+ "8121307687901225514249308620012025884376216406019656605767311580224"1979+ "4715304950770504195751384382230005665573033547124060755957932161045"1980+ "7288008201789401237690181537646952377591671113513382933711547044631"1981+ "6055957820531234310030119265612054594720774653570278810236807313332"1982+ "5293876225940483622056721445101719346295263740434720907474414905706"1983+ "086605825077661246082956613711071075569880930102141";1984private static final String RSA_2048_PRIV = "12265063405401593206575340300"1985+ "5824698296458954796982342251774894076489082263237675553422307220014"1986+ "4395010131540855227949365446755185799985229111139387016816011165826"1987+ "5498929552020323994756478872375078784799489891112924298115119573429"1988+ "3677627114115546751555523555375278381312502020990154549150867571006"1989+ "4470674155961982582802981649643127000520693025433874996570667724459"1990+ "3395670697152709457274026580106078581585077146782827694403672461289"1991+ "9143004401242754355097671446183871158504602884373174300123820136505"1992+ "6449932139773607305129273545117363975014750743804523418307647791195"1993+ "6408859873123458434820062206102268853256685162004893";1994private static final String EC_P256_X =1995"335863644451761614592446380116804721648611739647823420286081723541" +1996"6166183710";1997private static final String EC_P256_Y =1998"951559601159729477487064127150143688502130342917782252098602422796" +1999"95457910701";2000private static final String EC_P256_S =2001"425976209773168452211813225517384419928639977904006759709292218082" +2002"7440083936";2003private static final ECParameterSpec EC_P256_PARAMS = initECParams(2004"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",2005"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",2006"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B",2007"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",2008"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",2009"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551",201012011);2012private static final String EC_P384_X =2013"12144058647679082341340699736608428955270957565259459672517275506071643671835484144490620216582303669654008841724053";2014private static final String EC_P384_Y =2015"18287745972107701566600963632634101287058332546756092926848497481238534346489545826483592906634896557151987868614320";2016private static final String EC_P384_S =2017"10307785759830534742680442271492590599236624208247590184679565032330507874096079979152605984203102224450595283943382";2018private static final ECParameterSpec EC_P384_PARAMS = initECParams(2019"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF",2020"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC",2021"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF",2022"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7",2023"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F",2024"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973",202512026);2027private static final String EC_P521_X =2028"4157918188927862838251799402582135611021257663417126086145819679867926857146776190737187582274664373117054717389603317411991660346043842712448912355335343997";2029private static final String EC_P521_Y =2030"4102838062751704796157456866854813794620023146924181568434486703918224542844053923233919899911519054998554969832861957437850996213216829205401947264294066288";2031private static final String EC_P521_S =2032"4857798533181496041050215963883119936300918353498701880968530610687256097257307590162398707429640390843595868713096292822034014722985178583665959048714417342";2033private static final ECParameterSpec EC_P521_PARAMS = initECParams(2034"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",2035"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC",2036"0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00",2037"00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66",2038"011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650",2039"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409",204012041);20422043private static ECParameterSpec initECParams(2044String sfield, String a, String b, String gx, String gy,2045String n, int h) {2046ECField field = new ECFieldFp(bigInt(sfield));2047EllipticCurve curve = new EllipticCurve(field,2048bigInt(a), bigInt(b));2049ECPoint g = new ECPoint(bigInt(gx), bigInt(gy));2050return new ECParameterSpec(curve, g, bigInt(n), h);2051}20522053private static BigInteger bigInt(String s) {2054return new BigInteger(s, 16);2055}2056private static PublicKey getPublicKey(String algo, int keysize)2057throws Exception {2058KeyFactory kf = KeyFactory.getInstance(algo);2059KeySpec kspec;2060if (algo.equalsIgnoreCase("DSA")) {2061if (keysize == 1024) {2062kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),2063new BigInteger(DSA_P),2064new BigInteger(DSA_Q),2065new BigInteger(DSA_G));2066} else if (keysize == 2048) {2067kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y),2068new BigInteger(DSA_2048_P),2069new BigInteger(DSA_2048_Q),2070new BigInteger(DSA_2048_G));2071} else throw new RuntimeException("Unsupported keysize:" + keysize);2072} else if (algo.equalsIgnoreCase("RSA")) {2073if (keysize == 512) {2074kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD),2075new BigInteger(RSA_PUB));2076} else if (keysize == 1024) {2077kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),2078new BigInteger(RSA_PUB));2079} else if (keysize == 2048) {2080kspec = new RSAPublicKeySpec(new BigInteger(RSA_2048_MOD),2081new BigInteger(RSA_PUB));2082} else throw new RuntimeException("Unsupported keysize:" + keysize);2083} else throw new RuntimeException("Unsupported key algorithm " + algo);2084return kf.generatePublic(kspec);2085}20862087private static PublicKey getECPublicKey(String curve) throws Exception {2088KeyFactory kf = KeyFactory.getInstance("EC");2089String x, y;2090ECParameterSpec params;2091switch (curve) {2092case "P256":2093x = EC_P256_X;2094y = EC_P256_Y;2095params = EC_P256_PARAMS;2096break;2097case "P384":2098x = EC_P384_X;2099y = EC_P384_Y;2100params = EC_P384_PARAMS;2101break;2102case "P521":2103x = EC_P521_X;2104y = EC_P521_Y;2105params = EC_P521_PARAMS;2106break;2107default:2108throw new Exception("Unsupported curve: " + curve);2109}2110KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x),2111new BigInteger(y)),2112params);2113return kf.generatePublic(kspec);2114}21152116private static PrivateKey getPrivateKey(String algo, int keysize)2117throws Exception {2118KeyFactory kf = KeyFactory.getInstance(algo);2119KeySpec kspec;2120if (algo.equalsIgnoreCase("DSA")) {2121if (keysize == 1024) {2122kspec = new DSAPrivateKeySpec2123(new BigInteger(DSA_X), new BigInteger(DSA_P),2124new BigInteger(DSA_Q), new BigInteger(DSA_G));2125} else if (keysize == 2048) {2126kspec = new DSAPrivateKeySpec2127(new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P),2128new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));2129} else throw new RuntimeException("Unsupported keysize:" + keysize);2130} else if (algo.equalsIgnoreCase("RSA")) {2131if (keysize == 512) {2132kspec = new RSAPrivateKeySpec2133(new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV));2134} else if (keysize == 1024) {2135kspec = new RSAPrivateKeySpec(new BigInteger(RSA_1024_MOD),2136new BigInteger(RSA_1024_PRIV));2137} else if (keysize == 2048) {2138kspec = new RSAPrivateKeySpec(new BigInteger(RSA_2048_MOD),2139new BigInteger(RSA_2048_PRIV));2140} else throw new RuntimeException("Unsupported key algorithm " + algo);2141} else throw new RuntimeException("Unsupported key algorithm " + algo);2142return kf.generatePrivate(kspec);2143}21442145private static PrivateKey getECPrivateKey(String curve) throws Exception {2146String s;2147ECParameterSpec params;2148switch (curve) {2149case "P256":2150s = EC_P256_S;2151params = EC_P256_PARAMS;2152break;2153case "P384":2154s = EC_P384_S;2155params = EC_P384_PARAMS;2156break;2157case "P521":2158s = EC_P521_S;2159params = EC_P521_PARAMS;2160break;2161default:2162throw new Exception("Unsupported curve: " + curve);2163}2164KeyFactory kf = KeyFactory.getInstance("EC");2165KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);2166return kf.generatePrivate(kspec);2167}21682169private static SecretKey getSecretKey(final byte[] secret) {2170return new SecretKey() {2171public String getFormat() { return "RAW"; }2172public byte[] getEncoded() { return secret; }2173public String getAlgorithm(){ return "SECRET"; }2174};2175}21762177/**2178* This URIDereferencer returns locally cached copies of http content to2179* avoid test failures due to network glitches, etc.2180*/2181private static class HttpURIDereferencer implements URIDereferencer {2182private URIDereferencer defaultUd;21832184HttpURIDereferencer() {2185defaultUd = XMLSignatureFactory.getInstance().getURIDereferencer();2186}21872188public Data dereference(final URIReference ref, XMLCryptoContext ctx)2189throws URIReferenceException {2190String uri = ref.getURI();2191if (uri.equals(STYLESHEET) || uri.equals(STYLESHEET_B64)) {2192try {2193FileInputStream fis = new FileInputStream(new File2194(DATA_DIR, uri.substring(uri.lastIndexOf('/'))));2195return new OctetStreamData(fis,ref.getURI(),ref.getType());2196} catch (Exception e) { throw new URIReferenceException(e); }2197}21982199// fallback on builtin deref2200return defaultUd.dereference(ref, ctx);2201}2202}22032204// local http server2205static class Http implements HttpHandler, AutoCloseable {22062207private final HttpServer server;22082209private Http(HttpServer server) {2210this.server = server;2211}22122213static Http startServer() throws IOException {2214HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);2215return new Http(server);2216}22172218void start() {2219server.createContext("/", this);2220server.start();2221}22222223void stop() {2224server.stop(0);2225}22262227int getPort() {2228return server.getAddress().getPort();2229}22302231@Override2232public void handle(HttpExchange t) throws IOException {2233try {2234String type;2235String path = t.getRequestURI().getPath();2236if (path.startsWith("/")) {2237type = path.substring(1);2238} else {2239type = path;2240}22412242String contentTypeHeader = "";2243byte[] output = new byte[] {};2244int code = 200;2245Content testContentType = Content.valueOf(type);2246switch (testContentType) {2247case Base64:2248contentTypeHeader = "application/octet-stream";2249output = "VGVzdA==".getBytes();2250break;2251case Text:2252contentTypeHeader = "text/plain";2253output = "Text".getBytes();2254break;2255case Xml:2256contentTypeHeader = "application/xml";2257output = "<tag>test</tag>".getBytes();2258break;2259case NotExisitng:2260code = 404;2261break;2262default:2263throw new IOException("Unknown test content type");2264}22652266t.getResponseHeaders().set("Content-Type", contentTypeHeader);2267t.sendResponseHeaders(code, output.length);2268t.getResponseBody().write(output);2269} catch (IOException e) {2270System.out.println("Exception: " + e);2271t.sendResponseHeaders(500, 0);2272}2273t.close();2274}22752276@Override2277public void close() {2278stop();2279}2280}2281}228222832284