Path: blob/master/test/jdk/javax/xml/crypto/dsig/GenerationTests.java
66646 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.setURIDereferencer(httpUd);14571458XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);14591460if (sig.equals(sig2) == false) {1461throw new Exception1462("Unmarshalled signature is not equal to generated signature");1463}1464if (sig2.validate(dvc) == false) {1465throw new Exception("Validation of generated signature failed");1466}1467}14681469private static void test_create_signature_enveloping1470(DigestMethod dm, SignatureMethod sm, KeyInfo ki, Key signingKey,1471KeySelector ks, boolean b64, boolean secVal) throws Exception {14721473// create reference1474Reference ref;1475if (b64) {1476ref = fac.newReference("#object", dm, Collections.singletonList1477(fac.newTransform(Transform.BASE64,1478(TransformParameterSpec) null)), null, null);1479} else {1480ref = fac.newReference("#object", dm);1481}14821483// create SignedInfo1484SignedInfo si = fac.newSignedInfo(withoutComments, sm,1485Collections.singletonList(ref));14861487Document doc = db.newDocument();1488// create Objects1489String text = b64 ? "c29tZSB0ZXh0" : "some text";1490XMLObject obj = fac.newXMLObject(Collections.singletonList1491(new DOMStructure(doc.createTextNode(text))),1492"object", null, null);14931494// create XMLSignature1495XMLSignature sig = fac.newXMLSignature1496(si, ki, Collections.singletonList(obj), null, null);14971498DOMSignContext dsc = new DOMSignContext(signingKey, doc);14991500sig.sign(dsc);15011502// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));15031504DOMValidateContext dvc = new DOMValidateContext1505(ks, doc.getDocumentElement());1506dvc.setProperty("org.jcp.xml.dsig.secureValidation", secVal);1507XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);15081509if (sig.equals(sig2) == false) {1510throw new Exception1511("Unmarshalled signature is not equal to generated signature");1512}1513if (sig2.validate(dvc) == false) {1514throw new Exception("Validation of generated signature failed");1515}1516}15171518static void test_create_exc_signature() throws Exception {1519System.out.println("* Generating exc_signature.xml");1520List<Reference> refs = new ArrayList<>(4);15211522// create reference 11523refs.add(fac.newReference1524("#xpointer(id('to-be-signed'))", sha1,1525Collections.singletonList1526(fac.newTransform(CanonicalizationMethod.EXCLUSIVE,1527(TransformParameterSpec) null)),1528null, null));15291530// create reference 21531List<String> prefixList = new ArrayList<>(2);1532prefixList.add("bar");1533prefixList.add("#default");1534ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);1535refs.add(fac.newReference1536("#xpointer(id('to-be-signed'))", sha1,1537Collections.singletonList1538(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)),1539null, null));15401541// create reference 31542refs.add(fac.newReference1543("#xpointer(id('to-be-signed'))", sha1,1544Collections.singletonList(fac.newTransform1545(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,1546(TransformParameterSpec) null)),1547null, null));15481549// create reference 41550prefixList = new ArrayList<>(2);1551prefixList.add("bar");1552prefixList.add("#default");1553params = new ExcC14NParameterSpec(prefixList);1554refs.add(fac.newReference1555("#xpointer(id('to-be-signed'))", sha1,1556Collections.singletonList(fac.newTransform1557(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)),1558null, null));15591560// create SignedInfo1561SignedInfo si = fac.newSignedInfo(1562fac.newCanonicalizationMethod1563(CanonicalizationMethod.EXCLUSIVE,1564(C14NMethodParameterSpec) null),1565dsaSha1, refs);15661567// create KeyInfo1568List<XMLStructure> kits = new ArrayList<>(2);1569kits.add(kifac.newKeyValue(validatingKey));1570KeyInfo ki = kifac.newKeyInfo(kits);15711572// create Objects1573Document doc = db.newDocument();1574Element baz = doc.createElementNS("urn:bar", "bar:Baz");1575Comment com = doc.createComment(" comment ");1576baz.appendChild(com);1577XMLObject obj = fac.newXMLObject(Collections.singletonList1578(new DOMStructure(baz)), "to-be-signed", null, null);15791580// create XMLSignature1581XMLSignature sig = fac.newXMLSignature1582(si, ki, Collections.singletonList(obj), null, null);15831584Element foo = doc.createElementNS("urn:foo", "Foo");1585foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");1586foo.setAttributeNS1587("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");1588doc.appendChild(foo);15891590DOMSignContext dsc = new DOMSignContext(signingKey, foo);1591dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");15921593sig.sign(dsc);15941595// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));15961597DOMValidateContext dvc = new DOMValidateContext1598(new KeySelectors.KeyValueKeySelector(), foo.getLastChild());1599XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);16001601if (sig.equals(sig2) == false) {1602throw new Exception1603("Unmarshalled signature is not equal to generated signature");1604}1605if (sig2.validate(dvc) == false) {1606throw new Exception("Validation of generated signature failed");1607}1608System.out.println();1609}16101611static void test_create_sign_spec() throws Exception {1612System.out.println("* Generating sign-spec.xml");1613List<Reference> refs = new ArrayList<>(2);16141615// create reference 11616List<XPathType> types = new ArrayList<>(3);1617types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT));1618types.add(new XPathType(" //NotToBeSigned ",1619XPathType.Filter.SUBTRACT));1620types.add(new XPathType(" //ReallyToBeSigned ",1621XPathType.Filter.UNION));1622XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);1623refs.add(fac.newReference("", sha1,1624Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)),1625null, null));16261627// create reference 21628List<Transform> trans2 = new ArrayList<>(2);1629trans2.add(fac.newTransform(Transform.ENVELOPED,1630(TransformParameterSpec) null));1631XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec1632(Collections.singletonList1633(new XPathType(" / ", XPathType.Filter.UNION)));1634trans2.add(fac.newTransform(Transform.XPATH2, xp2));1635refs.add(fac.newReference("#signature-value", sha1, trans2, null, null));16361637// create SignedInfo1638SignedInfo si = fac.newSignedInfo(1639fac.newCanonicalizationMethod1640(CanonicalizationMethod.INCLUSIVE,1641(C14NMethodParameterSpec) null),1642dsaSha1, refs);16431644// create KeyInfo1645List<XMLStructure> kits = new ArrayList<>(2);1646kits.add(kifac.newKeyValue(validatingKey));1647List<Object> xds = new ArrayList<>(2);1648xds.add("CN=User");1649xds.add(signingCert);1650kits.add(kifac.newX509Data(xds));1651KeyInfo ki = kifac.newKeyInfo(kits);16521653// create XMLSignature1654XMLSignature sig = fac.newXMLSignature1655(si, ki, null, null, "signature-value");16561657Document doc = db.newDocument();1658Element tbs1 = doc.createElementNS(null, "ToBeSigned");1659Comment tbs1Com = doc.createComment(" comment ");1660Element tbs1Data = doc.createElementNS(null, "Data");1661Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned");1662Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned");1663Comment tbs1rtbsCom = doc.createComment(" comment ");1664Element tbs1rtbsData = doc.createElementNS(null, "Data");1665tbs1rtbs.appendChild(tbs1rtbsCom);1666tbs1rtbs.appendChild(tbs1rtbsData);1667tbs1ntbs.appendChild(tbs1rtbs);1668tbs1.appendChild(tbs1Com);1669tbs1.appendChild(tbs1Data);1670tbs1.appendChild(tbs1ntbs);16711672Element tbs2 = doc.createElementNS(null, "ToBeSigned");1673Element tbs2Data = doc.createElementNS(null, "Data");1674Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned");1675Element tbs2ntbsData = doc.createElementNS(null, "Data");1676tbs2ntbs.appendChild(tbs2ntbsData);1677tbs2.appendChild(tbs2Data);1678tbs2.appendChild(tbs2ntbs);16791680Element document = doc.createElementNS(null, "Document");1681document.appendChild(tbs1);1682document.appendChild(tbs2);1683doc.appendChild(document);16841685DOMSignContext dsc = new DOMSignContext(signingKey, document);16861687sig.sign(dsc);16881689// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));16901691DOMValidateContext dvc = new DOMValidateContext1692(new KeySelectors.KeyValueKeySelector(), document.getLastChild());1693XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);16941695if (sig.equals(sig2) == false) {1696throw new Exception1697("Unmarshalled signature is not equal to generated signature");1698}1699if (sig2.validate(dvc) == false) {1700throw new Exception("Validation of generated signature failed");1701}1702System.out.println();1703}17041705// Only print if there is an error.1706static void test_create_detached_signature(1707String canonicalizationMethod, String signatureMethod,1708String digestMethod, String transform, KeyInfoType keyInfo,1709Content contentType, int port, boolean expectedFailure,1710Class expectedException) {17111712String title = "\nTest detached signature:"1713+ "\n Canonicalization method: " + canonicalizationMethod1714+ "\n Signature method: " + signatureMethod1715+ "\n Transform: " + transform1716+ "\n Digest method: " + digestMethod1717+ "\n KeyInfoType: " + keyInfo1718+ "\n Content type: " + contentType1719+ "\n Expected failure: " + (expectedFailure ? "yes" : "no")1720+ "\n Expected exception: " + (expectedException == null ?1721"no" : expectedException.getName());17221723try {1724boolean success = test_create_detached_signature0(1725canonicalizationMethod,1726signatureMethod,1727digestMethod,1728transform,1729keyInfo,1730contentType,1731port);17321733if (success && expectedFailure) {1734System.out.println(title);1735System.out.println("Signature validation unexpectedly passed");1736result = false;1737} else if (!success && !expectedFailure) {1738System.out.println(title);1739System.out.println("Signature validation unexpectedly failed");1740result = false;1741} else if (expectedException != null) {1742System.out.println(title);1743System.out.println("Expected " + expectedException1744+ " not thrown");1745result = false;1746}1747} catch (Exception e) {1748if (expectedException == null1749|| !e.getClass().isAssignableFrom(expectedException)) {1750System.out.println(title);1751System.out.println("Unexpected exception: " + e);1752e.printStackTrace(System.out);1753result = false;1754}1755}1756}17571758// Print out as little as possible. This method will be called many times.1759static boolean test_create_detached_signature0(String canonicalizationMethod,1760String signatureMethod, String digestMethod, String transform,1761KeyInfoType keyInfo, Content contentType, int port)1762throws Exception {17631764System.out.print("-S");1765System.out.flush();17661767DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();1768dbf.setNamespaceAware(true);1769dbf.setValidating(false);17701771// Create SignedInfo1772DigestMethod dm = fac.newDigestMethod(digestMethod, null);17731774List transformList = null;1775if (transform != null) {1776TransformParameterSpec params = null;1777switch (transform) {1778case Transform.XPATH:1779params = new XPathFilterParameterSpec("//.");1780break;1781case Transform.XPATH2:1782params = new XPathFilter2ParameterSpec(1783Collections.singletonList(new XPathType("//.",1784XPathType.Filter.INTERSECT)));1785break;1786case Transform.XSLT:1787Element element = dbf.newDocumentBuilder()1788.parse(new ByteArrayInputStream(xslt.getBytes()))1789.getDocumentElement();1790DOMStructure stylesheet = new DOMStructure(element);1791params = new XSLTTransformParameterSpec(stylesheet);1792break;1793}1794transformList = Collections.singletonList(fac.newTransform(1795transform, params));1796}17971798String url = String.format("http://localhost:%d/%s", port, contentType);1799List refs = Collections.singletonList(fac.newReference(url, dm,1800transformList, null, null));18011802CanonicalizationMethod cm = fac.newCanonicalizationMethod(1803canonicalizationMethod, (C14NMethodParameterSpec) null);18041805SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);18061807Key[] pair = getCachedKeys(signatureMethod);1808Key signingKey = pair[0];1809Key validationKey = pair[1];18101811SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);18121813// Create KeyInfo1814KeyInfoFactory kif = fac.getKeyInfoFactory();1815List list = null;1816if (keyInfo == KeyInfoType.KeyValue) {1817if (validationKey instanceof PublicKey) {1818KeyValue kv = kif.newKeyValue((PublicKey) validationKey);1819list = Collections.singletonList(kv);1820}1821} else if (keyInfo == KeyInfoType.x509data) {1822list = Collections.singletonList(1823kif.newX509Data(Collections.singletonList("cn=Test")));1824} else if (keyInfo == KeyInfoType.KeyName) {1825list = Collections.singletonList(kif.newKeyName("Test"));1826} else {1827throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);1828}1829KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;18301831// Create an empty doc for detached signature1832Document doc = dbf.newDocumentBuilder().newDocument();1833DOMSignContext xsc = new DOMSignContext(signingKey, doc);18341835// Generate signature1836XMLSignature signature = fac.newXMLSignature(si, ki);1837signature.sign(xsc);18381839// Save signature1840String signatureString;1841try (StringWriter writer = new StringWriter()) {1842TransformerFactory tf = TransformerFactory.newInstance();1843Transformer trans = tf.newTransformer();1844Node parent = xsc.getParent();1845trans.transform(new DOMSource(parent), new StreamResult(writer));1846signatureString = writer.toString();1847}18481849System.out.print("V");1850System.out.flush();1851try (ByteArrayInputStream bis = new ByteArrayInputStream(1852signatureString.getBytes())) {1853doc = dbf.newDocumentBuilder().parse(bis);1854}18551856NodeList nodeLst = doc.getElementsByTagName("Signature");1857Node node = nodeLst.item(0);1858if (node == null) {1859throw new RuntimeException("Couldn't find Signature element");1860}1861if (!(node instanceof Element)) {1862throw new RuntimeException("Unexpected node type");1863}1864Element sig = (Element) node;18651866// Validate signature1867DOMValidateContext vc = new DOMValidateContext(validationKey, sig);1868vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);1869signature = fac.unmarshalXMLSignature(vc);18701871boolean success = signature.validate(vc);1872if (!success) {1873System.out.print("x");1874System.out.flush();1875return false;1876}18771878success = signature.getSignatureValue().validate(vc);1879if (!success) {1880System.out.print("X");1881System.out.flush();1882return false;1883}18841885return true;1886}18871888private static Key[] getCachedKeys(String signatureMethod) {1889return cachedKeys.computeIfAbsent(signatureMethod, sm -> {1890try {1891System.out.print("<create keys for " + sm + ">");1892System.out.flush();1893if (sm.contains("#hmac-")) {1894// http://...#hmac-sha1 -> hmac-sha1 -> hmacsha11895String algName = sm1896.substring(sm.indexOf('#') + 1)1897.replace("-", "");1898KeyGenerator kg = KeyGenerator.getInstance(algName);1899Key signingKey = kg.generateKey();1900return new Key[] { signingKey, signingKey};1901} else {1902KeyPairGenerator kpg;1903if (sm.contains("#rsa-")1904|| sm.contains("-rsa-MGF1")) {1905kpg = KeyPairGenerator.getInstance("RSA");1906kpg.initialize(1907sm.contains("#sha512-rsa-MGF1") ? 2048 : 1024);1908} else if (sm.contains("#dsa-")) {1909kpg = KeyPairGenerator.getInstance("DSA");1910kpg.initialize(1024);1911} else if (sm.contains("#ecdsa-")) {1912kpg = KeyPairGenerator.getInstance("EC");1913kpg.initialize(256);1914} else {1915throw new RuntimeException("Unsupported signature algorithm");1916}1917KeyPair kp = kpg.generateKeyPair();1918return new Key[] { kp.getPrivate(), kp.getPublic()};1919}1920} catch (NoSuchAlgorithmException e) {1921throw new AssertionError("Should not happen", e);1922}1923});1924}19251926private static final String DSA_Y =1927"070662842167565771936588335128634396171789331656318483584455493822" +1928"400811200853331373030669235424928346190274044631949560438023934623" +1929"71310375123430985057160";1930private static final String DSA_P =1931"013232376895198612407547930718267435757728527029623408872245156039" +1932"757713029036368719146452186041204237350521785240337048752071462798" +1933"273003935646236777459223";1934private static final String DSA_Q =1935"0857393771208094202104259627990318636601332086981";1936private static final String DSA_G =1937"054216440574364751416096484883257051280474283943804743768346673007" +1938"661082626139005426812890807137245973106730741193551360857959820973" +1939"90670890367185141189796";1940private static final String DSA_X =1941"0527140396812450214498055937934275626078768840117";1942private static final String DSA_2048_Y =1943"15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928";1944private static final String DSA_2048_P =1945"18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359";1946private static final String DSA_2048_Q =1947"19689526866605154788513693571065914024068069442724893395618704484701";1948private static final String DSA_2048_G =1949"2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430";1950private static final String DSA_2048_X =1951"14562787764977288900757387442281559936279834964901963465277698843172";1952private static final String RSA_MOD =1953"010800185049102889923150759252557522305032794699952150943573164381" +1954"936603255999071981574575044810461362008102247767482738822150129277" +1955"490998033971789476107463";1956private static final String RSA_PRIV =1957"016116973584421969795445996229612671947635798429212816611707210835" +1958"915586591340598683996088487065438751488342251960069575392056288063" +1959"6800379454345804879553";1960private static final String RSA_PUB = "065537";1961private static final String RSA_1024_MOD = "098871307553789439961130765" +1962"909423744508062468450669519128736624058048856940468016843888594585" +1963"322862378444314635412341974900625010364163960238734457710620107530" +1964"573945081856371709138380902553309075505688814637544923038853658690" +1965"857672483016239697038853418682988686871489963827000080098971762923" +1966"833614557257607521";1967private static final String RSA_1024_PRIV = "03682574144968491431483287" +1968"297021581096848810374110568017963075809477047466189822987258068867" +1969"704855380407747867998863645890602646601140183818953428006646987710" +1970"237008997971129772408397621801631622129297063463868593083106979716" +1971"204903524890556839550490384015324575598723478554854070823335021842" +1972"210112348400928769";1973private static final String RSA_2048_MOD = "243987087691547796017401146540"1974+ "9844666035826535295137885613771811531602666348704672255163984907599"1975+ "4298308997053582963763109207465354916871136820987101812436158377530"1976+ "6117270010853232249007544652859474372258057062943608962079402484091"1977+ "8121307687901225514249308620012025884376216406019656605767311580224"1978+ "4715304950770504195751384382230005665573033547124060755957932161045"1979+ "7288008201789401237690181537646952377591671113513382933711547044631"1980+ "6055957820531234310030119265612054594720774653570278810236807313332"1981+ "5293876225940483622056721445101719346295263740434720907474414905706"1982+ "086605825077661246082956613711071075569880930102141";1983private static final String RSA_2048_PRIV = "12265063405401593206575340300"1984+ "5824698296458954796982342251774894076489082263237675553422307220014"1985+ "4395010131540855227949365446755185799985229111139387016816011165826"1986+ "5498929552020323994756478872375078784799489891112924298115119573429"1987+ "3677627114115546751555523555375278381312502020990154549150867571006"1988+ "4470674155961982582802981649643127000520693025433874996570667724459"1989+ "3395670697152709457274026580106078581585077146782827694403672461289"1990+ "9143004401242754355097671446183871158504602884373174300123820136505"1991+ "6449932139773607305129273545117363975014750743804523418307647791195"1992+ "6408859873123458434820062206102268853256685162004893";1993private static final String EC_P256_X =1994"335863644451761614592446380116804721648611739647823420286081723541" +1995"6166183710";1996private static final String EC_P256_Y =1997"951559601159729477487064127150143688502130342917782252098602422796" +1998"95457910701";1999private static final String EC_P256_S =2000"425976209773168452211813225517384419928639977904006759709292218082" +2001"7440083936";2002private static final ECParameterSpec EC_P256_PARAMS = initECParams(2003"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",2004"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",2005"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B",2006"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",2007"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",2008"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551",200912010);2011private static final String EC_P384_X =2012"12144058647679082341340699736608428955270957565259459672517275506071643671835484144490620216582303669654008841724053";2013private static final String EC_P384_Y =2014"18287745972107701566600963632634101287058332546756092926848497481238534346489545826483592906634896557151987868614320";2015private static final String EC_P384_S =2016"10307785759830534742680442271492590599236624208247590184679565032330507874096079979152605984203102224450595283943382";2017private static final ECParameterSpec EC_P384_PARAMS = initECParams(2018"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF",2019"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC",2020"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF",2021"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7",2022"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F",2023"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973",202412025);2026private static final String EC_P521_X =2027"4157918188927862838251799402582135611021257663417126086145819679867926857146776190737187582274664373117054717389603317411991660346043842712448912355335343997";2028private static final String EC_P521_Y =2029"4102838062751704796157456866854813794620023146924181568434486703918224542844053923233919899911519054998554969832861957437850996213216829205401947264294066288";2030private static final String EC_P521_S =2031"4857798533181496041050215963883119936300918353498701880968530610687256097257307590162398707429640390843595868713096292822034014722985178583665959048714417342";2032private static final ECParameterSpec EC_P521_PARAMS = initECParams(2033"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",2034"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC",2035"0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00",2036"00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66",2037"011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650",2038"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409",203912040);20412042private static ECParameterSpec initECParams(2043String sfield, String a, String b, String gx, String gy,2044String n, int h) {2045ECField field = new ECFieldFp(bigInt(sfield));2046EllipticCurve curve = new EllipticCurve(field,2047bigInt(a), bigInt(b));2048ECPoint g = new ECPoint(bigInt(gx), bigInt(gy));2049return new ECParameterSpec(curve, g, bigInt(n), h);2050}20512052private static BigInteger bigInt(String s) {2053return new BigInteger(s, 16);2054}2055private static PublicKey getPublicKey(String algo, int keysize)2056throws Exception {2057KeyFactory kf = KeyFactory.getInstance(algo);2058KeySpec kspec;2059if (algo.equalsIgnoreCase("DSA")) {2060if (keysize == 1024) {2061kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),2062new BigInteger(DSA_P),2063new BigInteger(DSA_Q),2064new BigInteger(DSA_G));2065} else if (keysize == 2048) {2066kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y),2067new BigInteger(DSA_2048_P),2068new BigInteger(DSA_2048_Q),2069new BigInteger(DSA_2048_G));2070} else throw new RuntimeException("Unsupported keysize:" + keysize);2071} else if (algo.equalsIgnoreCase("RSA")) {2072if (keysize == 512) {2073kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD),2074new BigInteger(RSA_PUB));2075} else if (keysize == 1024) {2076kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),2077new BigInteger(RSA_PUB));2078} else if (keysize == 2048) {2079kspec = new RSAPublicKeySpec(new BigInteger(RSA_2048_MOD),2080new BigInteger(RSA_PUB));2081} else throw new RuntimeException("Unsupported keysize:" + keysize);2082} else throw new RuntimeException("Unsupported key algorithm " + algo);2083return kf.generatePublic(kspec);2084}20852086private static PublicKey getECPublicKey(String curve) throws Exception {2087KeyFactory kf = KeyFactory.getInstance("EC");2088String x, y;2089ECParameterSpec params;2090switch (curve) {2091case "P256":2092x = EC_P256_X;2093y = EC_P256_Y;2094params = EC_P256_PARAMS;2095break;2096case "P384":2097x = EC_P384_X;2098y = EC_P384_Y;2099params = EC_P384_PARAMS;2100break;2101case "P521":2102x = EC_P521_X;2103y = EC_P521_Y;2104params = EC_P521_PARAMS;2105break;2106default:2107throw new Exception("Unsupported curve: " + curve);2108}2109KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x),2110new BigInteger(y)),2111params);2112return kf.generatePublic(kspec);2113}21142115private static PrivateKey getPrivateKey(String algo, int keysize)2116throws Exception {2117KeyFactory kf = KeyFactory.getInstance(algo);2118KeySpec kspec;2119if (algo.equalsIgnoreCase("DSA")) {2120if (keysize == 1024) {2121kspec = new DSAPrivateKeySpec2122(new BigInteger(DSA_X), new BigInteger(DSA_P),2123new BigInteger(DSA_Q), new BigInteger(DSA_G));2124} else if (keysize == 2048) {2125kspec = new DSAPrivateKeySpec2126(new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P),2127new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));2128} else throw new RuntimeException("Unsupported keysize:" + keysize);2129} else if (algo.equalsIgnoreCase("RSA")) {2130if (keysize == 512) {2131kspec = new RSAPrivateKeySpec2132(new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV));2133} else if (keysize == 1024) {2134kspec = new RSAPrivateKeySpec(new BigInteger(RSA_1024_MOD),2135new BigInteger(RSA_1024_PRIV));2136} else if (keysize == 2048) {2137kspec = new RSAPrivateKeySpec(new BigInteger(RSA_2048_MOD),2138new BigInteger(RSA_2048_PRIV));2139} else throw new RuntimeException("Unsupported key algorithm " + algo);2140} else throw new RuntimeException("Unsupported key algorithm " + algo);2141return kf.generatePrivate(kspec);2142}21432144private static PrivateKey getECPrivateKey(String curve) throws Exception {2145String s;2146ECParameterSpec params;2147switch (curve) {2148case "P256":2149s = EC_P256_S;2150params = EC_P256_PARAMS;2151break;2152case "P384":2153s = EC_P384_S;2154params = EC_P384_PARAMS;2155break;2156case "P521":2157s = EC_P521_S;2158params = EC_P521_PARAMS;2159break;2160default:2161throw new Exception("Unsupported curve: " + curve);2162}2163KeyFactory kf = KeyFactory.getInstance("EC");2164KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);2165return kf.generatePrivate(kspec);2166}21672168private static SecretKey getSecretKey(final byte[] secret) {2169return new SecretKey() {2170public String getFormat() { return "RAW"; }2171public byte[] getEncoded() { return secret; }2172public String getAlgorithm(){ return "SECRET"; }2173};2174}21752176/**2177* This URIDereferencer returns locally cached copies of http content to2178* avoid test failures due to network glitches, etc.2179*/2180private static class HttpURIDereferencer implements URIDereferencer {2181private URIDereferencer defaultUd;21822183HttpURIDereferencer() {2184defaultUd = XMLSignatureFactory.getInstance().getURIDereferencer();2185}21862187public Data dereference(final URIReference ref, XMLCryptoContext ctx)2188throws URIReferenceException {2189String uri = ref.getURI();2190if (uri.equals(STYLESHEET) || uri.equals(STYLESHEET_B64)) {2191try {2192FileInputStream fis = new FileInputStream(new File2193(DATA_DIR, uri.substring(uri.lastIndexOf('/'))));2194return new OctetStreamData(fis,ref.getURI(),ref.getType());2195} catch (Exception e) { throw new URIReferenceException(e); }2196} else if (uri.startsWith("certs/")) {2197try {2198FileInputStream fis = new FileInputStream(new File2199(DATA_DIR, uri));2200return new OctetStreamData(fis,ref.getURI(),ref.getType());2201} catch (Exception e) { throw new URIReferenceException(e); }2202}22032204// fallback on builtin deref2205return defaultUd.dereference(ref, ctx);2206}2207}22082209// local http server2210static class Http implements HttpHandler, AutoCloseable {22112212private final HttpServer server;22132214private Http(HttpServer server) {2215this.server = server;2216}22172218static Http startServer() throws IOException {2219HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);2220return new Http(server);2221}22222223void start() {2224server.createContext("/", this);2225server.start();2226}22272228void stop() {2229server.stop(0);2230}22312232int getPort() {2233return server.getAddress().getPort();2234}22352236@Override2237public void handle(HttpExchange t) throws IOException {2238try {2239String type;2240String path = t.getRequestURI().getPath();2241if (path.startsWith("/")) {2242type = path.substring(1);2243} else {2244type = path;2245}22462247String contentTypeHeader = "";2248byte[] output = new byte[] {};2249int code = 200;2250Content testContentType = Content.valueOf(type);2251switch (testContentType) {2252case Base64:2253contentTypeHeader = "application/octet-stream";2254output = "VGVzdA==".getBytes();2255break;2256case Text:2257contentTypeHeader = "text/plain";2258output = "Text".getBytes();2259break;2260case Xml:2261contentTypeHeader = "application/xml";2262output = "<tag>test</tag>".getBytes();2263break;2264case NotExisitng:2265code = 404;2266break;2267default:2268throw new IOException("Unknown test content type");2269}22702271t.getResponseHeaders().set("Content-Type", contentTypeHeader);2272t.sendResponseHeaders(code, output.length);2273t.getResponseBody().write(output);2274} catch (IOException e) {2275System.out.println("Exception: " + e);2276t.sendResponseHeaders(500, 0);2277}2278t.close();2279}22802281@Override2282public void close() {2283stop();2284}2285}2286}228722882289