Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/javax/xml/crypto/dsig/GenerationTests.java
38853 views
/*1* Copyright (c) 2005, 2019, 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 803818426* 8038349 8046724 8074784 8079693 8177334 8205507 8210736 821787827* @summary Basic unit tests for generating XML Signatures with JSR 10528* @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java29* X509KeySelector.java GenerationTests.java30* @run main/othervm/timeout=300 -Dsun.net.httpserver.nodelay=true GenerationTests31* @author Sean Mullan32*/3334import com.sun.net.httpserver.HttpExchange;35import com.sun.net.httpserver.HttpHandler;36import com.sun.net.httpserver.HttpServer;37import java.io.*;38import java.lang.reflect.Modifier;39import java.math.BigInteger;40import java.net.InetSocketAddress;41import java.security.Key;42import java.security.KeyFactory;43import java.security.KeyPair;44import java.security.KeyPairGenerator;45import java.security.KeyStore;46import java.security.NoSuchAlgorithmException;47import java.security.PrivateKey;48import java.security.PublicKey;49import java.security.SecureRandom;50import java.security.Security;51import java.security.cert.Certificate;52import java.security.cert.CertificateFactory;53import java.security.cert.X509CRL;54import java.security.spec.KeySpec;55import java.security.spec.DSAPrivateKeySpec;56import java.security.spec.DSAPublicKeySpec;57import java.security.spec.ECField;58import java.security.spec.ECFieldFp;59import java.security.spec.ECParameterSpec;60import java.security.spec.ECPoint;61import java.security.spec.ECPrivateKeySpec;62import java.security.spec.ECPublicKeySpec;63import java.security.spec.EllipticCurve;64import java.security.spec.RSAPrivateKeySpec;65import java.security.spec.RSAPublicKeySpec;66import java.util.*;67import java.util.stream.Stream;68import javax.crypto.KeyGenerator;69import javax.crypto.SecretKey;70import javax.xml.XMLConstants;71import javax.xml.parsers.*;72import javax.xml.crypto.Data;73import javax.xml.crypto.KeySelector;74import javax.xml.crypto.OctetStreamData;75import javax.xml.crypto.URIDereferencer;76import javax.xml.crypto.URIReference;77import javax.xml.crypto.URIReferenceException;78import javax.xml.crypto.XMLCryptoContext;79import javax.xml.crypto.XMLStructure;80import javax.xml.crypto.dsig.*;81import javax.xml.crypto.dom.*;82import javax.xml.crypto.dsig.dom.DOMSignContext;83import javax.xml.crypto.dsig.dom.DOMValidateContext;84import javax.xml.crypto.dsig.keyinfo.*;85import javax.xml.crypto.dsig.spec.*;86import javax.xml.transform.*;87import javax.xml.transform.dom.DOMSource;88import javax.xml.transform.stream.StreamResult;89import org.w3c.dom.*;9091/**92* Test that recreates merlin-xmldsig-twenty-three test vectors (and more)93* but with different keys and X.509 data.94*/95public class GenerationTests {9697private static XMLSignatureFactory fac;98private static KeyInfoFactory kifac;99private static DocumentBuilder db;100private static CanonicalizationMethod withoutComments;101private static SignatureMethod dsaSha1, dsaSha256,102rsaSha1, rsaSha224, rsaSha256, rsaSha384, rsaSha512,103ecdsaSha1, ecdsaSha224, ecdsaSha256, ecdsaSha384, ecdsaSha512,104hmacSha1, hmacSha224, hmacSha256, hmacSha384, hmacSha512,105rsaSha1mgf1, rsaSha224mgf1, rsaSha256mgf1, rsaSha384mgf1, rsaSha512mgf1;106private static DigestMethod sha1, sha224, sha256, sha384, sha512;107private static KeyInfo dsa1024, dsa2048, rsa, rsa1024, rsa2048,108p256ki, p384ki, p521ki;109private static KeySelector kvks = new KeySelectors.KeyValueKeySelector();110private static KeySelector sks;111private static Key signingKey;112private static PublicKey validatingKey;113private static Certificate signingCert;114private static KeyStore ks;115private final static String DIR = System.getProperty("test.src", ".");116// private final static String DIR = ".";117private final static String DATA_DIR =118DIR + System.getProperty("file.separator") + "data";119private final static String KEYSTORE =120DATA_DIR + System.getProperty("file.separator") + "certs" +121System.getProperty("file.separator") + "test.jks";122private final static String CRL =123DATA_DIR + System.getProperty("file.separator") + "certs" +124System.getProperty("file.separator") + "crl";125// XML Document with a DOCTYPE declaration126private final static String ENVELOPE =127DATA_DIR + System.getProperty("file.separator") + "envelope.xml";128// XML Document without a DOCTYPE declaration129private final static String ENVELOPE2 =130DATA_DIR + System.getProperty("file.separator") + "envelope2.xml";131private static URIDereferencer httpUd = null;132private final static String STYLESHEET =133"http://www.w3.org/TR/xml-stylesheet";134private final static String STYLESHEET_B64 =135"http://www.w3.org/Signature/2002/04/xml-stylesheet.b64";136private final static String DSA_SHA256 =137"http://www.w3.org/2009/xmldsig11#dsa-sha256";138139private static final String BOGUS = "bogus";140141private static final String OS = System.getProperty("os.name");142private static boolean secondChanceGranted = false;143144private static final String xslt = ""145+ "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'\n"146+ " xmlns='http://www.w3.org/TR/xhtml1/strict' \n"147+ " exclude-result-prefixes='foo' \n"148+ " version='1.0'>\n"149+ " <xsl:output encoding='UTF-8' \n"150+ " indent='no' \n"151+ " method='xml' />\n"152+ " <xsl:template match='/'>\n"153+ " <html>\n"154+ " <head>\n"155+ " <title>Notaries</title>\n"156+ " </head>\n"157+ " <body>\n"158+ " <table>\n"159+ " <xsl:for-each select='Notaries/Notary'>\n"160+ " <tr>\n"161+ " <th>\n"162+ " <xsl:value-of select='@name' />\n"163+ " </th>\n"164+ " </tr>\n"165+ " </xsl:for-each>\n"166+ " </table>\n"167+ " </body>\n"168+ " </html>\n"169+ " </xsl:template>\n"170+ "</xsl:stylesheet>\n";171172private static final String[] canonicalizationMethods = new String[] {173CanonicalizationMethod.EXCLUSIVE,174CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,175CanonicalizationMethod.INCLUSIVE,176CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS177};178179private static final String[] xml_transforms = new String[] {180Transform.XSLT,181Transform.XPATH,182Transform.XPATH2,183CanonicalizationMethod.EXCLUSIVE,184CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,185CanonicalizationMethod.INCLUSIVE,186CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,187};188189private static final String[] non_xml_transforms = new String[] {190null, Transform.BASE64191};192193// It will be too time consuming to test all combinations of194// all digest methods and signature methods. So we pick some195// majors one and only test a combination when a major method196// (either digest or signature) is included.197//198// * * *199// * * *200// * * *201// * * * * * * * * *202// * * * * * * * * *203// * * * * * * * * *204// * * *205// * * *206// * * *207208private static List<String> majorSignatureMethods;209static {210List<String> tmpList = Arrays.asList(211"http://www.w3.org/2009/xmldsig11#dsa-sha256",212"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",213"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256",214"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",215"http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1");216majorSignatureMethods = Collections.unmodifiableList(tmpList);217}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;232static {233List<String> tmpList = Arrays.asList(234DigestMethod.SHA1,235DigestMethod.SHA256);236majorDigestMethods = Collections.unmodifiableList(tmpList);237}238239private static final String[] allDigestMethods240= Stream.of(DigestMethod.class.getDeclaredFields())241.filter(f -> Modifier.isStatic(f.getModifiers())242&& !f.getName().equals("RIPEMD160"))243.map(f -> {244try {245return (String)f.get(null);246} catch (Exception e) {247throw new Error("should not happen");248}249})250.toArray(String[]::new);251252// As of JDK 8, the number of defined algorithms are...253static {254if (allSignatureMethods.length != 3255|| allDigestMethods.length != 3) {256System.out.println(Arrays.toString(allSignatureMethods));257System.out.println(Arrays.toString(allDigestMethods));258throw new AssertionError("Not all methods are counted");259}260}261262private static enum Content {263Xml, Text, Base64, NotExisitng264}265266private static enum KeyInfoType {267KeyValue, x509data, KeyName268}269270// cached keys (for performance) used by test_create_detached_signature().271private static HashMap<String,Key[]> cachedKeys = new HashMap<>();272273// Load cachedKeys persisted in a file to reproduce a failure.274// The keys are always saved to "cached-keys" but you can rename275// it to a different file name and load it here. Note: The keys will276// always be persisted so renaming is a good idea although the277// content might not change.278static {279String cacheFile = System.getProperty("use.cached.keys");280if (cacheFile != null) {281try (FileInputStream fis = new FileInputStream(cacheFile);282ObjectInputStream ois = new ObjectInputStream(fis)) {283cachedKeys = (HashMap<String,Key[]>) ois.readObject();284} catch (Exception e) {285throw new AssertionError("Cannot read " + cacheFile, e);286}287}288}289290private static boolean result = true;291292public static void main(String args[]) throws Exception {293setup();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_sha512_rsa_sha384();327test_create_signature_enveloping_sha512_rsa_sha224();328test_create_signature_enveloping_sha512_rsa_sha512();329test_create_signature_enveloping_sha512_rsa_sha1_mgf1();330test_create_signature_enveloping_sha512_rsa_sha224_mgf1();331test_create_signature_enveloping_sha512_rsa_sha256_mgf1();332test_create_signature_enveloping_sha512_rsa_sha384_mgf1();333test_create_signature_enveloping_sha512_rsa_sha512_mgf1();334test_create_signature_reference_dependency();335test_create_signature_with_attr_in_no_namespace();336test_create_signature_with_empty_id();337test_create_signature_enveloping_over_doc(ENVELOPE, true);338test_create_signature_enveloping_over_doc(ENVELOPE2, true);339test_create_signature_enveloping_over_doc(ENVELOPE, false);340test_create_signature_enveloping_dom_level1();341342// run tests for detached signatures with local http server343try (Http server = Http.startServer()) {344server.start();345346// tests for XML documents347Arrays.stream(canonicalizationMethods).forEach(c ->348Arrays.stream(allSignatureMethods).forEach(s ->349Arrays.stream(allDigestMethods).forEach(d ->350Arrays.stream(xml_transforms).forEach(t ->351Arrays.stream(KeyInfoType.values()).forEach(k -> {352if (isMajor(s, d)) {353test_create_detached_signature(c, s, d, t, k,354Content.Xml, server.getPort(), false, null);355}356})))));357358// tests for text data with no transform359Arrays.stream(canonicalizationMethods).forEach(c ->360Arrays.stream(allSignatureMethods).forEach(s ->361Arrays.stream(allDigestMethods).forEach(d ->362Arrays.stream(KeyInfoType.values()).forEach(k -> {363if (isMajor(s, d)) {364test_create_detached_signature(c, s, d, null, k,365Content.Text, server.getPort(), false, null);366}367}))));368369// tests for base64 data370Arrays.stream(canonicalizationMethods).forEach(c ->371Arrays.stream(allSignatureMethods).forEach(s ->372Arrays.stream(allDigestMethods).forEach(d ->373Arrays.stream(non_xml_transforms).forEach(t ->374Arrays.stream(KeyInfoType.values()).forEach(k -> {375if (isMajor(s, d)) {376test_create_detached_signature(c, s, d, t, k,377Content.Base64, server.getPort(),378false, null);379}380})))));381382// negative tests383384// unknown CanonicalizationMethod385test_create_detached_signature(386CanonicalizationMethod.EXCLUSIVE + BOGUS,387SignatureMethod.DSA_SHA1,388DigestMethod.SHA1,389CanonicalizationMethod.INCLUSIVE,390KeyInfoType.KeyName,391Content.Xml,392server.getPort(),393true,394NoSuchAlgorithmException.class);395396// unknown SignatureMethod397test_create_detached_signature(398CanonicalizationMethod.EXCLUSIVE,399SignatureMethod.DSA_SHA1 + BOGUS,400DigestMethod.SHA1,401CanonicalizationMethod.INCLUSIVE,402KeyInfoType.KeyName, Content.Xml,403server.getPort(),404true,405NoSuchAlgorithmException.class);406407// unknown DigestMethod408test_create_detached_signature(409CanonicalizationMethod.EXCLUSIVE,410SignatureMethod.DSA_SHA1,411DigestMethod.SHA1 + BOGUS,412CanonicalizationMethod.INCLUSIVE,413KeyInfoType.KeyName, Content.Xml,414server.getPort(),415true,416NoSuchAlgorithmException.class);417418// unknown Transform419test_create_detached_signature(420CanonicalizationMethod.EXCLUSIVE,421SignatureMethod.DSA_SHA1,422DigestMethod.SHA1,423CanonicalizationMethod.INCLUSIVE + BOGUS,424KeyInfoType.KeyName, Content.Xml,425server.getPort(),426true,427NoSuchAlgorithmException.class);428429// no source document430test_create_detached_signature(431CanonicalizationMethod.EXCLUSIVE,432SignatureMethod.DSA_SHA1,433DigestMethod.SHA1,434CanonicalizationMethod.INCLUSIVE,435KeyInfoType.KeyName,436Content.NotExisitng,437server.getPort(),438true,439XMLSignatureException.class);440441// wrong transform for text data442test_create_detached_signature(443CanonicalizationMethod.EXCLUSIVE,444SignatureMethod.DSA_SHA1,445DigestMethod.SHA1,446CanonicalizationMethod.INCLUSIVE,447KeyInfoType.KeyName,448Content.Text,449server.getPort(),450true,451XMLSignatureException.class);452}453454// persist cached keys to a file.455try (FileOutputStream fos = new FileOutputStream("cached-keys", true);456ObjectOutputStream oos = new ObjectOutputStream(fos)) {457oos.writeObject(cachedKeys);458}459460if (!result) {461throw new RuntimeException("At least one test case failed");462}463}464465// Do not test on all combinations.466private static boolean isMajor(String signatureMethod, String digestMethod) {467return majorDigestMethods.contains(digestMethod)468|| majorSignatureMethods.contains(signatureMethod);469}470471private static void setup() throws Exception {472fac = XMLSignatureFactory.getInstance();473kifac = fac.getKeyInfoFactory();474DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();475dbf.setNamespaceAware(true);476db = dbf.newDocumentBuilder();477478// get key & self-signed certificate from keystore479FileInputStream fis = new FileInputStream(KEYSTORE);480ks = KeyStore.getInstance("JKS");481ks.load(fis, "changeit".toCharArray());482signingKey = ks.getKey("user", "changeit".toCharArray());483signingCert = ks.getCertificate("user");484validatingKey = signingCert.getPublicKey();485486// create common objects487withoutComments = fac.newCanonicalizationMethod488(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null);489dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null);490dsaSha256 = fac.newSignatureMethod(DSA_SHA256, null);491492sha1 = fac.newDigestMethod(DigestMethod.SHA1, null);493sha224 = fac.newDigestMethod("http://www.w3.org/2001/04/xmldsig-more#sha224", null);494sha256 = fac.newDigestMethod(DigestMethod.SHA256, null);495sha384 = fac.newDigestMethod("http://www.w3.org/2001/04/xmldsig-more#sha384", null);496sha512 = fac.newDigestMethod(DigestMethod.SHA512, null);497498dsa1024 = kifac.newKeyInfo(Collections.singletonList499(kifac.newKeyValue(validatingKey)));500dsa2048 = kifac.newKeyInfo(Collections.singletonList501(kifac.newKeyValue(getPublicKey("DSA", 2048))));502rsa = kifac.newKeyInfo(Collections.singletonList503(kifac.newKeyValue(getPublicKey("RSA", 512))));504rsa1024 = kifac.newKeyInfo(Collections.singletonList505(kifac.newKeyValue(getPublicKey("RSA", 1024))));506rsa2048 = kifac.newKeyInfo(Collections.singletonList507(kifac.newKeyValue(getPublicKey("RSA", 2048))));508p256ki = kifac.newKeyInfo(Collections.singletonList509(kifac.newKeyValue(getECPublicKey("P256"))));510p384ki = kifac.newKeyInfo(Collections.singletonList511(kifac.newKeyValue(getECPublicKey("P384"))));512p521ki = kifac.newKeyInfo(Collections.singletonList513(kifac.newKeyValue(getECPublicKey("P521"))));514515rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null);516rsaSha224 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha224", null);517rsaSha256 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null);518rsaSha384 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384", null);519rsaSha512 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512", null);520521rsaSha1mgf1 = fac.newSignatureMethod("http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1", null);522rsaSha224mgf1 = fac.newSignatureMethod("http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1", null);523rsaSha256mgf1 = fac.newSignatureMethod("http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1", null);524rsaSha384mgf1 = fac.newSignatureMethod("http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1", null);525rsaSha512mgf1 = fac.newSignatureMethod("http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1", null);526527ecdsaSha1 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1", null);528ecdsaSha224 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224", null);529ecdsaSha256 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256", null);530ecdsaSha384 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384", null);531ecdsaSha512 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512", null);532533hmacSha1 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA1, null);534hmacSha224 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha224", null);535hmacSha256 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", null);536hmacSha384 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", null);537hmacSha512 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", null);538539sks = new KeySelectors.SecretKeySelector("secret".getBytes("ASCII"));540541httpUd = new HttpURIDereferencer();542}543544static void test_create_signature_enveloped_dsa(int size) throws Exception {545System.out.println("* Generating signature-enveloped-dsa-"546+ size + ".xml");547SignatureMethod sm = null;548KeyInfo ki = null;549Key privKey;550if (size == 1024) {551sm = dsaSha1;552ki = dsa1024;553privKey = signingKey;554} else if (size == 2048) {555sm = dsaSha256;556ki = dsa2048;557privKey = getPrivateKey("DSA", 2048);558} else throw new RuntimeException("unsupported keysize:" + size);559560// create SignedInfo561SignedInfo si = fac.newSignedInfo562(withoutComments, sm, Collections.singletonList563(fac.newReference564("", sha1, Collections.singletonList565(fac.newTransform(Transform.ENVELOPED,566(TransformParameterSpec) null)),567null, null)));568569// create XMLSignature570XMLSignature sig = fac.newXMLSignature(si, ki);571572Document doc = db.newDocument();573Element envelope = doc.createElementNS574("http://example.org/envelope", "Envelope");575envelope.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,576"xmlns", "http://example.org/envelope");577doc.appendChild(envelope);578579DOMSignContext dsc = new DOMSignContext(privKey, envelope);580581sig.sign(dsc);582// StringWriter sw = new StringWriter();583// dumpDocument(doc, sw);584// System.out.println(sw.toString());585586DOMValidateContext dvc = new DOMValidateContext587(kvks, envelope.getFirstChild());588XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);589590if (sig.equals(sig2) == false) {591throw new Exception592("Unmarshalled signature is not equal to generated signature");593}594595if (sig2.validate(dvc) == false) {596throw new Exception("Validation of generated signature failed");597}598System.out.println();599}600601static void test_create_signature_enveloping_b64_dsa() throws Exception {602System.out.println("* Generating signature-enveloping-b64-dsa.xml");603test_create_signature_enveloping604(sha1, dsaSha1, dsa1024, signingKey, kvks, true);605System.out.println();606}607608static void test_create_signature_enveloping_dsa() throws Exception {609System.out.println("* Generating signature-enveloping-dsa.xml");610test_create_signature_enveloping611(sha1, dsaSha1, dsa1024, signingKey, kvks, false);612System.out.println();613}614615static void test_create_signature_enveloping_sha256_dsa() throws Exception {616System.out.println("* Generating signature-enveloping-sha256-dsa.xml");617test_create_signature_enveloping618(sha256, dsaSha1, dsa1024, signingKey, kvks, false);619System.out.println();620}621622static void test_create_signature_enveloping_hmac_sha1_40()623throws Exception {624System.out.println("* Generating signature-enveloping-hmac-sha1-40.xml");625try {626test_create_signature_enveloping(sha1, hmacSha1, null,627getSecretKey("secret".getBytes("ASCII")), sks, false);628} catch (Exception e) {629if (!(e instanceof XMLSignatureException)) {630throw e;631}632}633System.out.println();634}635636static void test_create_signature_enveloping_hmac_sha256()637throws Exception {638System.out.println("* Generating signature-enveloping-hmac-sha256.xml");639test_create_signature_enveloping(sha1, hmacSha256, null,640getSecretKey("secret".getBytes("ASCII")), sks, false);641System.out.println();642}643644static void test_create_signature_enveloping_hmac_sha224()645throws Exception {646System.out.println("* Generating signature-enveloping-hmac-sha224.xml");647test_create_signature_enveloping(sha1, hmacSha224, null,648getSecretKey("secret".getBytes("ASCII")), sks, false);649System.out.println();650}651652static void test_create_signature_enveloping_hmac_sha384()653throws Exception {654System.out.println("* Generating signature-enveloping-hmac-sha384.xml");655test_create_signature_enveloping(sha1, hmacSha384, null,656getSecretKey("secret".getBytes("ASCII")), sks, false);657System.out.println();658}659660static void test_create_signature_enveloping_hmac_sha512()661throws Exception {662System.out.println("* Generating signature-enveloping-hmac-sha512.xml");663test_create_signature_enveloping(sha1, hmacSha512, null,664getSecretKey("secret".getBytes("ASCII")), sks, false);665System.out.println();666}667668static void test_create_signature_enveloping_rsa() throws Exception {669System.out.println("* Generating signature-enveloping-rsa.xml");670test_create_signature_enveloping(sha1, rsaSha1, rsa,671getPrivateKey("RSA", 512), kvks, false);672System.out.println();673}674675static void test_create_signature_enveloping_sha384_rsa_sha256()676throws Exception {677System.out.println("* Generating signature-enveloping-sha384-rsa_sha256.xml");678test_create_signature_enveloping(sha384, rsaSha256, rsa,679getPrivateKey("RSA", 512), kvks, false);680System.out.println();681}682683static void test_create_signature_enveloping_sha224_rsa_sha256()684throws Exception {685System.out.println("* Generating signature-enveloping-sha224-rsa_sha256.xml");686test_create_signature_enveloping(sha224, rsaSha256, rsa,687getPrivateKey("RSA", 512), kvks, false);688System.out.println();689}690691static void test_create_signature_enveloping_sha512_rsa_sha384()692throws Exception {693System.out.println("* Generating signature-enveloping-sha512-rsa_sha384.xml");694test_create_signature_enveloping(sha512, rsaSha384, rsa1024,695getPrivateKey("RSA", 1024), kvks, false);696System.out.println();697}698699static void test_create_signature_enveloping_sha512_rsa_sha224()700throws Exception {701System.out.println("* Generating signature-enveloping-sha512-rsa_sha224.xml");702test_create_signature_enveloping(sha512, rsaSha224, rsa1024,703getPrivateKey("RSA", 1024), kvks, false);704System.out.println();705}706707static void test_create_signature_enveloping_sha512_rsa_sha512()708throws Exception {709System.out.println("* Generating signature-enveloping-sha512-rsa_sha512.xml");710test_create_signature_enveloping(sha512, rsaSha512, rsa1024,711getPrivateKey("RSA", 1024), kvks, false);712System.out.println();713}714715static void test_create_signature_enveloping_sha512_rsa_sha1_mgf1()716throws Exception {717System.out.println("* Generating signature-enveloping-sha512-rsa_sha1_mgf1.xml");718test_create_signature_enveloping(sha512, rsaSha1mgf1, rsa1024,719getPrivateKey("RSA", 1024), kvks, false);720System.out.println();721}722723static void test_create_signature_enveloping_sha512_rsa_sha224_mgf1()724throws Exception {725System.out.println("* Generating signature-enveloping-sha512-rsa_sha224_mgf1.xml");726test_create_signature_enveloping(sha512, rsaSha224mgf1, rsa1024,727getPrivateKey("RSA", 1024), kvks, false);728System.out.println();729}730731static void test_create_signature_enveloping_sha512_rsa_sha256_mgf1()732throws Exception {733System.out.println("* Generating signature-enveloping-sha512-rsa_sha256_mgf1.xml");734test_create_signature_enveloping(sha512, rsaSha256mgf1, rsa1024,735getPrivateKey("RSA", 1024), kvks, false);736System.out.println();737}738739static void test_create_signature_enveloping_sha512_rsa_sha384_mgf1()740throws Exception {741System.out.println("* Generating signature-enveloping-sha512-rsa_sha384_mgf1.xml");742test_create_signature_enveloping(sha512, rsaSha384mgf1, rsa1024,743getPrivateKey("RSA", 1024), kvks, false);744System.out.println();745}746747static void test_create_signature_enveloping_sha512_rsa_sha512_mgf1()748throws Exception {749System.out.println("* Generating signature-enveloping-sha512-rsa_sha512_mgf1.xml");750test_create_signature_enveloping(sha512, rsaSha512mgf1, rsa2048,751getPrivateKey("RSA", 2048), kvks, false);752System.out.println();753}754755static void test_create_signature_enveloping_p256_sha1() throws Exception {756System.out.println("* Generating signature-enveloping-p256-sha1.xml");757test_create_signature_enveloping(sha1, ecdsaSha1, p256ki,758getECPrivateKey("P256"), kvks, false);759System.out.println();760}761762static void test_create_signature_enveloping_p256_sha224() throws Exception {763System.out.println("* Generating signature-enveloping-p256-sha224.xml");764test_create_signature_enveloping(sha1, ecdsaSha224, p256ki,765getECPrivateKey("P256"), kvks, false);766System.out.println();767}768769static void test_create_signature_enveloping_p256_sha256() throws Exception {770System.out.println("* Generating signature-enveloping-p256-sha256.xml");771test_create_signature_enveloping(sha1, ecdsaSha256, p256ki,772getECPrivateKey("P256"), kvks, false);773System.out.println();774}775776static void test_create_signature_enveloping_p256_sha384() throws Exception {777System.out.println("* Generating signature-enveloping-p256-sha384.xml");778test_create_signature_enveloping(sha1, ecdsaSha384, p256ki,779getECPrivateKey("P256"), kvks, false);780System.out.println();781}782783static void test_create_signature_enveloping_p256_sha512() throws Exception {784System.out.println("* Generating signature-enveloping-p256-sha512.xml");785test_create_signature_enveloping(sha1, ecdsaSha512, p256ki,786getECPrivateKey("P256"), kvks, false);787System.out.println();788}789790static void test_create_signature_enveloping_p384_sha1() throws Exception {791System.out.println("* Generating signature-enveloping-p384-sha1.xml");792test_create_signature_enveloping(sha1, ecdsaSha1, p384ki,793getECPrivateKey("P384"), kvks, false);794System.out.println();795}796797static void test_create_signature_enveloping_p521_sha1() throws Exception {798System.out.println("* Generating signature-enveloping-p521-sha1.xml");799test_create_signature_enveloping(sha1, ecdsaSha1, p521ki,800getECPrivateKey("P521"), kvks, false);801System.out.println();802}803804static void test_create_signature_external_b64_dsa() throws Exception {805System.out.println("* Generating signature-external-b64-dsa.xml");806test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, true);807System.out.println();808}809810static void test_create_signature_external_dsa() throws Exception {811System.out.println("* Generating signature-external-dsa.xml");812test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, false);813System.out.println();814}815816static void test_create_signature_keyname() throws Exception {817System.out.println("* Generating signature-keyname.xml");818KeyInfo kn = kifac.newKeyInfo(Collections.singletonList819(kifac.newKeyName("user")));820test_create_signature_external(dsaSha1, kn, signingKey,821new X509KeySelector(ks), false);822System.out.println();823}824825static void test_create_signature_retrievalmethod_rawx509crt()826throws Exception {827System.out.println(828"* Generating signature-retrievalmethod-rawx509crt.xml");829KeyInfo rm = kifac.newKeyInfo(Collections.singletonList830(kifac.newRetrievalMethod831("certs/user.crt", X509Data.RAW_X509_CERTIFICATE_TYPE, null)));832test_create_signature_external(dsaSha1, rm, signingKey,833new X509KeySelector(ks), false);834System.out.println();835}836837static void test_create_signature_x509_crt_crl() throws Exception {838System.out.println("* Generating signature-x509-crt-crl.xml");839List<Object> xds = new ArrayList<Object>();840CertificateFactory cf = CertificateFactory.getInstance("X.509");841xds.add(signingCert);842FileInputStream fis = new FileInputStream(CRL);843X509CRL crl = (X509CRL) cf.generateCRL(fis);844fis.close();845xds.add(crl);846KeyInfo crt_crl = kifac.newKeyInfo(Collections.singletonList847(kifac.newX509Data(xds)));848849test_create_signature_external(dsaSha1, crt_crl, signingKey,850new X509KeySelector(ks), false);851System.out.println();852}853854static void test_create_signature_x509_crt() throws Exception {855System.out.println("* Generating signature-x509-crt.xml");856KeyInfo crt = kifac.newKeyInfo(Collections.singletonList857(kifac.newX509Data(Collections.singletonList(signingCert))));858859test_create_signature_external(dsaSha1, crt, signingKey,860new X509KeySelector(ks), false);861System.out.println();862}863864static void test_create_signature_x509_is() throws Exception {865System.out.println("* Generating signature-x509-is.xml");866KeyInfo is = kifac.newKeyInfo(Collections.singletonList867(kifac.newX509Data(Collections.singletonList868(kifac.newX509IssuerSerial869("CN=User", new BigInteger("45ef2729", 16))))));870test_create_signature_external(dsaSha1, is, signingKey,871new X509KeySelector(ks), false);872System.out.println();873}874875static void test_create_signature_x509_ski() throws Exception {876System.out.println("* Generating signature-x509-ski.xml");877KeyInfo ski = kifac.newKeyInfo(Collections.singletonList878(kifac.newX509Data(Collections.singletonList879("keyid".getBytes("ASCII")))));880881test_create_signature_external(dsaSha1, ski, signingKey,882KeySelector.singletonKeySelector(validatingKey), false);883System.out.println();884}885886static void test_create_signature_x509_sn() throws Exception {887System.out.println("* Generating signature-x509-sn.xml");888KeyInfo sn = kifac.newKeyInfo(Collections.singletonList889(kifac.newX509Data(Collections.singletonList("CN=User"))));890891test_create_signature_external(dsaSha1, sn, signingKey,892new X509KeySelector(ks), false);893System.out.println();894}895896static void test_create_signature_reference_dependency() throws Exception {897System.out.println("* Generating signature-reference-dependency.xml");898// create references899List<Reference> refs = Collections.singletonList900(fac.newReference("#object-1", sha1));901902// create SignedInfo903SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);904905// create objects906List<XMLStructure> objs = new ArrayList<XMLStructure>();907908// Object 1909List<Reference> manRefs = Collections.singletonList910(fac.newReference("#object-2", sha1));911objs.add(fac.newXMLObject(Collections.singletonList912(fac.newManifest(manRefs, "manifest-1")), "object-1", null, null));913914// Object 2915Document doc = db.newDocument();916Element nc = doc.createElementNS(null, "NonCommentandus");917nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");918nc.appendChild(doc.createComment(" Commentandum "));919objs.add(fac.newXMLObject(Collections.singletonList920(new DOMStructure(nc)), "object-2", null, null));921922// create XMLSignature923XMLSignature sig = fac.newXMLSignature(si, rsa, objs, "signature", null);924DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);925926sig.sign(dsc);927928// dumpDocument(doc, new PrintWriter(System.out));929930DOMValidateContext dvc = new DOMValidateContext931(kvks, doc.getDocumentElement());932XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);933934if (sig.equals(sig2) == false) {935throw new Exception936("Unmarshalled signature is not equal to generated signature");937}938if (sig2.validate(dvc) == false) {939throw new Exception("Validation of generated signature failed");940}941942System.out.println();943}944945static void test_create_signature_with_attr_in_no_namespace()946throws Exception947{948System.out.println949("* Generating signature-with-attr-in-no-namespace.xml");950951// create references952List<Reference> refs = Collections.singletonList953(fac.newReference("#unknown", sha1));954955// create SignedInfo956SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);957958// create object-1959Document doc = db.newDocument();960Element nc = doc.createElementNS(null, "NonCommentandus");961// add attribute with no namespace962nc.setAttribute("Id", "unknown");963XMLObject obj = fac.newXMLObject(Collections.singletonList964(new DOMStructure(nc)), "object-1", null, null);965966// create XMLSignature967XMLSignature sig = fac.newXMLSignature(si, rsa,968Collections.singletonList(obj),969"signature", null);970DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);971dsc.setIdAttributeNS(nc, null, "Id");972973sig.sign(dsc);974975// dumpDocument(doc, new PrintWriter(System.out));976977DOMValidateContext dvc = new DOMValidateContext978(kvks, doc.getDocumentElement());979dvc.setIdAttributeNS(nc, null, "Id");980XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);981982if (sig.equals(sig2) == false) {983throw new Exception984("Unmarshalled signature is not equal to generated signature");985}986if (sig2.validate(dvc) == false) {987throw new Exception("Validation of generated signature failed");988}989990System.out.println();991}992993static void test_create_signature_with_empty_id() throws Exception {994System.out.println("* Generating signature-with-empty-id.xml");995996// create references997List<Reference> refs = Collections.singletonList998(fac.newReference("#", sha1));9991000// create SignedInfo1001SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);10021003// create object with empty id1004Document doc = db.newDocument();1005XMLObject obj = fac.newXMLObject(Collections.singletonList1006(new DOMStructure(doc.createTextNode("I am the text."))),1007"", "text/plain", null);10081009// create XMLSignature1010XMLSignature sig = fac.newXMLSignature(si, rsa,1011Collections.singletonList(obj),1012"signature", null);1013DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);1014sig.sign(dsc);10151016System.out.println();1017}10181019static void test_create_signature_enveloping_over_doc(String filename,1020boolean pass) throws Exception1021{1022System.out.println("* Generating signature-enveloping-over-doc.xml");10231024// create reference1025Reference ref = fac.newReference("#object", sha256);10261027// create SignedInfo1028SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha256,1029Collections.singletonList(ref));10301031// create object1032Document doc = null;1033try (FileInputStream fis = new FileInputStream(filename)) {1034doc = db.parse(fis);1035}1036DOMStructure ds = pass ? new DOMStructure(doc.getDocumentElement())1037: new DOMStructure(doc);1038XMLObject obj = fac.newXMLObject(Collections.singletonList(ds),1039"object", null, "UTF-8");10401041// This creates an enveloping signature over the entire XML Document1042XMLSignature sig = fac.newXMLSignature(si, rsa,1043Collections.singletonList(obj),1044"signature", null);1045DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 1024), doc);1046try {1047sig.sign(dsc);1048if (!pass) {1049// A Document node can only exist at the root of the doc so this1050// should fail1051throw new Exception("Test unexpectedly passed");1052}1053} catch (Exception e) {1054if (!pass) {1055System.out.println("Test failed as expected: " + e);1056} else {1057throw e;1058}1059}10601061if (pass) {1062DOMValidateContext dvc = new DOMValidateContext1063(getPublicKey("RSA", 1024), doc.getDocumentElement());1064XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);10651066if (sig.equals(sig2) == false) {1067throw new Exception1068("Unmarshalled signature is not equal to generated signature");1069}1070if (sig2.validate(dvc) == false) {1071throw new Exception("Validation of generated signature failed");1072}1073}10741075System.out.println();1076}10771078static void test_create_signature_enveloping_dom_level1() throws Exception {1079System.out.println("* Generating signature-enveloping-dom-level1.xml");10801081// create reference1082Reference ref = fac.newReference("#object", sha256);10831084// create SignedInfo1085SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha256,1086Collections.singletonList(ref));10871088// create object using DOM Level 1 methods1089Document doc = db.newDocument();1090Element child = doc.createElement("Child");1091child.setAttribute("Version", "1.0");1092child.setAttribute("Id", "child");1093child.setIdAttribute("Id", true);1094child.appendChild(doc.createComment("Comment"));1095XMLObject obj = fac.newXMLObject(1096Collections.singletonList(new DOMStructure(child)),1097"object", null, "UTF-8");10981099XMLSignature sig = fac.newXMLSignature(si, rsa,1100Collections.singletonList(obj),1101"signature", null);1102DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 1024), doc);1103sig.sign(dsc);11041105DOMValidateContext dvc = new DOMValidateContext1106(getPublicKey("RSA", 1024), doc.getDocumentElement());1107XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);11081109if (sig.equals(sig2) == false) {1110throw new Exception1111("Unmarshalled signature is not equal to generated signature");1112}1113if (sig2.validate(dvc) == false) {1114throw new Exception("Validation of generated signature failed");1115}11161117System.out.println();1118}11191120static void test_create_signature() throws Exception {1121System.out.println("* Generating signature.xml");11221123// create references1124List<Reference> refs = new ArrayList<Reference>();11251126// Reference 11127refs.add(fac.newReference(STYLESHEET, sha1));11281129// Reference 21130refs.add(fac.newReference1131(STYLESHEET_B64,1132sha1, Collections.singletonList1133(fac.newTransform(Transform.BASE64,1134(TransformParameterSpec) null)), null, null));11351136// Reference 31137refs.add(fac.newReference("#object-1", sha1, Collections.singletonList1138(fac.newTransform(Transform.XPATH,1139new XPathFilterParameterSpec("self::text()"))),1140XMLObject.TYPE, null));11411142// Reference 41143String expr = "\n"1144+ " ancestor-or-self::dsig:SignedInfo " + "\n"1145+ " and " + "\n"1146+ " count(ancestor-or-self::dsig:Reference | " + "\n"1147+ " here()/ancestor::dsig:Reference[1]) > " + "\n"1148+ " count(ancestor-or-self::dsig:Reference) " + "\n"1149+ " or " + "\n"1150+ " count(ancestor-or-self::node() | " + "\n"1151+ " id('notaries')) = " + "\n"1152+ " count(ancestor-or-self::node()) " + "\n";11531154XPathFilterParameterSpec xfp = new XPathFilterParameterSpec(expr,1155Collections.singletonMap("dsig", XMLSignature.XMLNS));1156refs.add(fac.newReference("", sha1, Collections.singletonList1157(fac.newTransform(Transform.XPATH, xfp)),1158XMLObject.TYPE, null));11591160// Reference 51161refs.add(fac.newReference("#object-2", sha1, Collections.singletonList1162(fac.newTransform1163(Transform.BASE64, (TransformParameterSpec) null)),1164XMLObject.TYPE, null));11651166// Reference 61167refs.add(fac.newReference1168("#manifest-1", sha1, null, Manifest.TYPE, null));11691170// Reference 71171refs.add(fac.newReference("#signature-properties-1", sha1, null,1172SignatureProperties.TYPE, null));11731174// Reference 81175List<Transform> transforms = new ArrayList<Transform>();1176transforms.add(fac.newTransform1177(Transform.ENVELOPED, (TransformParameterSpec) null));1178refs.add(fac.newReference("", sha1, transforms, null, null));11791180// Reference 91181transforms.add(fac.newTransform1182(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,1183(TransformParameterSpec) null));1184refs.add(fac.newReference("", sha1, transforms, null, null));11851186// Reference 101187Transform env = fac.newTransform1188(Transform.ENVELOPED, (TransformParameterSpec) null);1189refs.add(fac.newReference("#xpointer(/)",1190sha1, Collections.singletonList(env), null, null));11911192// Reference 111193transforms.clear();1194transforms.add(fac.newTransform1195(Transform.ENVELOPED, (TransformParameterSpec) null));1196transforms.add(fac.newTransform1197(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,1198(TransformParameterSpec) null));1199refs.add(fac.newReference("#xpointer(/)", sha1, transforms,1200null, null));12011202// Reference 121203refs.add1204(fac.newReference("#object-3", sha1, null, XMLObject.TYPE, null));12051206// Reference 131207Transform withComments = fac.newTransform1208(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,1209(TransformParameterSpec) null);1210refs.add(fac.newReference("#object-3", sha1,1211Collections.singletonList(withComments), XMLObject.TYPE, null));12121213// Reference 141214refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, null,1215XMLObject.TYPE, null));12161217// Reference 151218withComments = fac.newTransform1219(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,1220(TransformParameterSpec) null);1221refs.add(fac.newReference("#xpointer(id('object-3'))", sha1,1222Collections.singletonList(withComments), XMLObject.TYPE, null));12231224// Reference 161225refs.add(fac.newReference("#reference-2", sha1));12261227// Reference 171228refs.add(fac.newReference("#manifest-reference-1", sha1, null,1229null, "reference-1"));12301231// Reference 181232refs.add(fac.newReference("#reference-1", sha1, null, null,1233"reference-2"));12341235// create SignedInfo1236SignedInfo si = fac.newSignedInfo(withoutComments, dsaSha1, refs);12371238// create keyinfo1239XPathFilterParameterSpec xpf = new XPathFilterParameterSpec(1240"ancestor-or-self::dsig:X509Data",1241Collections.singletonMap("dsig", XMLSignature.XMLNS));1242RetrievalMethod rm = kifac.newRetrievalMethod("#object-4",1243X509Data.TYPE, Collections.singletonList(fac.newTransform1244(Transform.XPATH, xpf)));1245KeyInfo ki = kifac.newKeyInfo(Collections.singletonList(rm), null);12461247Document doc = db.newDocument();12481249// create objects1250List<XMLStructure> objs = new ArrayList<XMLStructure>();12511252// Object 11253objs.add(fac.newXMLObject(Collections.singletonList1254(new DOMStructure(doc.createTextNode("I am the text."))),1255"object-1", "text/plain", null));12561257// Object 21258objs.add(fac.newXMLObject(Collections.singletonList1259(new DOMStructure(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="))),1260"object-2", "text/plain", Transform.BASE64));12611262// Object 31263Element nc = doc.createElementNS(null, "NonCommentandus");1264nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");1265nc.appendChild(doc.createComment(" Commentandum "));1266objs.add(fac.newXMLObject(Collections.singletonList1267(new DOMStructure(nc)), "object-3", null, null));12681269// Manifest1270List<Reference> manRefs = new ArrayList<Reference>();12711272// Manifest Reference 11273manRefs.add(fac.newReference(STYLESHEET,1274sha1, null, null, "manifest-reference-1"));12751276// Manifest Reference 21277manRefs.add(fac.newReference("#reference-1", sha1));12781279// Manifest Reference 31280List<Transform> manTrans = new ArrayList<Transform>();1281Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));1282Node xslElem = docxslt.getDocumentElement();12831284manTrans.add(fac.newTransform(Transform.XSLT,1285new XSLTTransformParameterSpec(new DOMStructure(xslElem))));1286manTrans.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE,1287(TransformParameterSpec) null));1288manRefs.add(fac.newReference("#notaries", sha1, manTrans, null, null));12891290objs.add(fac.newXMLObject(Collections.singletonList1291(fac.newManifest(manRefs, "manifest-1")), null, null, null));12921293// SignatureProperties1294Element sa = doc.createElementNS("urn:demo", "SignerAddress");1295sa.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:demo");1296Element ip = doc.createElementNS("urn:demo", "IP");1297ip.appendChild(doc.createTextNode("192.168.21.138"));1298sa.appendChild(ip);1299SignatureProperty sp = fac.newSignatureProperty1300(Collections.singletonList(new DOMStructure(sa)),1301"#signature", null);1302SignatureProperties sps = fac.newSignatureProperties1303(Collections.singletonList(sp), "signature-properties-1");1304objs.add(fac.newXMLObject(Collections.singletonList(sps), null,1305null, null));13061307// Object 41308List<Object> xds = new ArrayList<Object>();1309xds.add("CN=User");1310xds.add(kifac.newX509IssuerSerial1311("CN=User", new BigInteger("45ef2729", 16)));1312xds.add(signingCert);1313objs.add(fac.newXMLObject(Collections.singletonList1314(kifac.newX509Data(xds)), "object-4", null, null));13151316// create XMLSignature1317XMLSignature sig = fac.newXMLSignature(si, ki, objs, "signature", null);13181319DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();1320dbf.setNamespaceAware(true);1321dbf.setValidating(false);1322Document envDoc = dbf.newDocumentBuilder().parse1323(new FileInputStream(ENVELOPE));1324Element ys = (Element)1325envDoc.getElementsByTagName("YoursSincerely").item(0);13261327DOMSignContext dsc = new DOMSignContext(signingKey, ys);1328dsc.setURIDereferencer(httpUd);13291330sig.sign(dsc);13311332// StringWriter sw = new StringWriter();1333// dumpDocument(envDoc, sw);13341335NodeList nl =1336envDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");1337if (nl.getLength() == 0) {1338throw new Exception("Couldn't find signature Element");1339}1340Element sigElement = (Element) nl.item(0);13411342DOMValidateContext dvc = new DOMValidateContext1343(new X509KeySelector(ks), sigElement);1344dvc.setURIDereferencer(httpUd);1345File f = new File(1346System.getProperty("dir.test.vector.baltimore") +1347System.getProperty("file.separator") +1348"merlin-xmldsig-twenty-three" +1349System.getProperty("file.separator"));1350dvc.setBaseURI(f.toURI().toString());13511352XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);13531354if (sig.equals(sig2) == false) {1355throw new Exception1356("Unmarshalled signature is not equal to generated signature");1357}1358if (sig2.validate(dvc) == false) {1359throw new Exception("Validation of generated signature failed");1360}1361System.out.println();1362}13631364private static void dumpDocument(Document doc, Writer w) throws Exception {1365TransformerFactory tf = TransformerFactory.newInstance();1366Transformer trans = tf.newTransformer();1367// trans.setOutputProperty(OutputKeys.INDENT, "yes");1368trans.transform(new DOMSource(doc), new StreamResult(w));1369}13701371private static void test_create_signature_external1372(SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks,1373boolean b64) throws Exception {13741375// create reference1376Reference ref;1377if (b64) {1378ref = fac.newReference1379(STYLESHEET_B64,1380sha1, Collections.singletonList1381(fac.newTransform(Transform.BASE64,1382(TransformParameterSpec) null)), null, null);1383} else {1384ref = fac.newReference(STYLESHEET, sha1);1385}13861387// create SignedInfo1388SignedInfo si = fac.newSignedInfo(withoutComments, sm,1389Collections.singletonList(ref));13901391Document doc = db.newDocument();13921393// create XMLSignature1394XMLSignature sig = fac.newXMLSignature(si, ki);13951396DOMSignContext dsc = new DOMSignContext(signingKey, doc);1397dsc.setURIDereferencer(httpUd);13981399sig.sign(dsc);14001401DOMValidateContext dvc = new DOMValidateContext1402(ks, doc.getDocumentElement());1403File f = new File(DATA_DIR);1404dvc.setBaseURI(f.toURI().toString());1405dvc.setURIDereferencer(httpUd);14061407XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);14081409if (sig.equals(sig2) == false) {1410throw new Exception1411("Unmarshalled signature is not equal to generated signature");1412}1413if (sig2.validate(dvc) == false) {1414throw new Exception("Validation of generated signature failed");1415}1416}14171418private static void test_create_signature_enveloping1419(DigestMethod dm, SignatureMethod sm, KeyInfo ki, Key signingKey,1420KeySelector ks, boolean b64) throws Exception {14211422// create reference1423Reference ref;1424if (b64) {1425ref = fac.newReference("#object", dm, Collections.singletonList1426(fac.newTransform(Transform.BASE64,1427(TransformParameterSpec) null)), null, null);1428} else {1429ref = fac.newReference("#object", dm);1430}14311432// create SignedInfo1433SignedInfo si = fac.newSignedInfo(withoutComments, sm,1434Collections.singletonList(ref));14351436Document doc = db.newDocument();1437// create Objects1438String text = b64 ? "c29tZSB0ZXh0" : "some text";1439XMLObject obj = fac.newXMLObject(Collections.singletonList1440(new DOMStructure(doc.createTextNode(text))),1441"object", null, null);14421443// create XMLSignature1444XMLSignature sig = fac.newXMLSignature1445(si, ki, Collections.singletonList(obj), null, null);14461447DOMSignContext dsc = new DOMSignContext(signingKey, doc);14481449sig.sign(dsc);14501451// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));14521453DOMValidateContext dvc = new DOMValidateContext1454(ks, doc.getDocumentElement());1455XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);14561457if (sig.equals(sig2) == false) {1458throw new Exception1459("Unmarshalled signature is not equal to generated signature");1460}1461if (sig2.validate(dvc) == false) {1462throw new Exception("Validation of generated signature failed");1463}1464}14651466static void test_create_exc_signature() throws Exception {1467System.out.println("* Generating exc_signature.xml");1468List<Reference> refs = new ArrayList<Reference>(4);14691470// create reference 11471refs.add(fac.newReference1472("#xpointer(id('to-be-signed'))", sha1,1473Collections.singletonList1474(fac.newTransform(CanonicalizationMethod.EXCLUSIVE,1475(TransformParameterSpec) null)),1476null, null));14771478// create reference 21479List<String> prefixList = new ArrayList<String>(2);1480prefixList.add("bar");1481prefixList.add("#default");1482ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);1483refs.add(fac.newReference1484("#xpointer(id('to-be-signed'))", sha1,1485Collections.singletonList1486(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)),1487null, null));14881489// create reference 31490refs.add(fac.newReference1491("#xpointer(id('to-be-signed'))", sha1,1492Collections.singletonList(fac.newTransform1493(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,1494(TransformParameterSpec) null)),1495null, null));14961497// create reference 41498prefixList = new ArrayList<String>(2);1499prefixList.add("bar");1500prefixList.add("#default");1501params = new ExcC14NParameterSpec(prefixList);1502refs.add(fac.newReference1503("#xpointer(id('to-be-signed'))", sha1,1504Collections.singletonList(fac.newTransform1505(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)),1506null, null));15071508// create SignedInfo1509SignedInfo si = fac.newSignedInfo(1510fac.newCanonicalizationMethod1511(CanonicalizationMethod.EXCLUSIVE,1512(C14NMethodParameterSpec) null),1513dsaSha1, refs);15141515// create KeyInfo1516List<XMLStructure> kits = new ArrayList<XMLStructure>(2);1517kits.add(kifac.newKeyValue(validatingKey));1518KeyInfo ki = kifac.newKeyInfo(kits);15191520// create Objects1521Document doc = db.newDocument();1522Element baz = doc.createElementNS("urn:bar", "bar:Baz");1523Comment com = doc.createComment(" comment ");1524baz.appendChild(com);1525XMLObject obj = fac.newXMLObject(Collections.singletonList1526(new DOMStructure(baz)), "to-be-signed", null, null);15271528// create XMLSignature1529XMLSignature sig = fac.newXMLSignature1530(si, ki, Collections.singletonList(obj), null, null);15311532Element foo = doc.createElementNS("urn:foo", "Foo");1533foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");1534foo.setAttributeNS1535("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");1536doc.appendChild(foo);15371538DOMSignContext dsc = new DOMSignContext(signingKey, foo);1539dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");15401541sig.sign(dsc);15421543// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));15441545DOMValidateContext dvc = new DOMValidateContext1546(new KeySelectors.KeyValueKeySelector(), foo.getLastChild());1547XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);15481549if (sig.equals(sig2) == false) {1550throw new Exception1551("Unmarshalled signature is not equal to generated signature");1552}1553if (sig2.validate(dvc) == false) {1554throw new Exception("Validation of generated signature failed");1555}1556System.out.println();1557}15581559static void test_create_sign_spec() throws Exception {1560System.out.println("* Generating sign-spec.xml");1561List<Reference> refs = new ArrayList<Reference>(2);15621563// create reference 11564List<XPathType> types = new ArrayList<XPathType>(3);1565types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT));1566types.add(new XPathType(" //NotToBeSigned ",1567XPathType.Filter.SUBTRACT));1568types.add(new XPathType(" //ReallyToBeSigned ",1569XPathType.Filter.UNION));1570XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);1571refs.add(fac.newReference("", sha1,1572Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)),1573null, null));15741575// create reference 21576List<Transform> trans2 = new ArrayList<Transform>(2);1577trans2.add(fac.newTransform(Transform.ENVELOPED,1578(TransformParameterSpec) null));1579XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec1580(Collections.singletonList1581(new XPathType(" / ", XPathType.Filter.UNION)));1582trans2.add(fac.newTransform(Transform.XPATH2, xp2));1583refs.add(fac.newReference("#signature-value", sha1, trans2, null, null));15841585// create SignedInfo1586SignedInfo si = fac.newSignedInfo(1587fac.newCanonicalizationMethod1588(CanonicalizationMethod.INCLUSIVE,1589(C14NMethodParameterSpec) null),1590dsaSha1, refs);15911592// create KeyInfo1593List<XMLStructure> kits = new ArrayList<XMLStructure>(2);1594kits.add(kifac.newKeyValue(validatingKey));1595List<Object> xds = new ArrayList<Object>(2);1596xds.add("CN=User");1597xds.add(signingCert);1598kits.add(kifac.newX509Data(xds));1599KeyInfo ki = kifac.newKeyInfo(kits);16001601// create XMLSignature1602XMLSignature sig = fac.newXMLSignature1603(si, ki, null, null, "signature-value");16041605Document doc = db.newDocument();1606Element tbs1 = doc.createElementNS(null, "ToBeSigned");1607Comment tbs1Com = doc.createComment(" comment ");1608Element tbs1Data = doc.createElementNS(null, "Data");1609Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned");1610Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned");1611Comment tbs1rtbsCom = doc.createComment(" comment ");1612Element tbs1rtbsData = doc.createElementNS(null, "Data");1613tbs1rtbs.appendChild(tbs1rtbsCom);1614tbs1rtbs.appendChild(tbs1rtbsData);1615tbs1ntbs.appendChild(tbs1rtbs);1616tbs1.appendChild(tbs1Com);1617tbs1.appendChild(tbs1Data);1618tbs1.appendChild(tbs1ntbs);16191620Element tbs2 = doc.createElementNS(null, "ToBeSigned");1621Element tbs2Data = doc.createElementNS(null, "Data");1622Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned");1623Element tbs2ntbsData = doc.createElementNS(null, "Data");1624tbs2ntbs.appendChild(tbs2ntbsData);1625tbs2.appendChild(tbs2Data);1626tbs2.appendChild(tbs2ntbs);16271628Element document = doc.createElementNS(null, "Document");1629document.appendChild(tbs1);1630document.appendChild(tbs2);1631doc.appendChild(document);16321633DOMSignContext dsc = new DOMSignContext(signingKey, document);16341635sig.sign(dsc);16361637// dumpDocument(doc, new FileWriter("/tmp/foo.xml"));16381639DOMValidateContext dvc = new DOMValidateContext1640(new KeySelectors.KeyValueKeySelector(), document.getLastChild());1641XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);16421643if (sig.equals(sig2) == false) {1644throw new Exception1645("Unmarshalled signature is not equal to generated signature");1646}1647if (sig2.validate(dvc) == false) {1648throw new Exception("Validation of generated signature failed");1649}1650System.out.println();1651}16521653// Only print if there is an error.1654static void test_create_detached_signature(1655String canonicalizationMethod, String signatureMethod,1656String digestMethod, String transform, KeyInfoType keyInfo,1657Content contentType, int port, boolean expectedFailure,1658Class expectedException) {16591660String title = "\nTest detached signature:"1661+ "\n Canonicalization method: " + canonicalizationMethod1662+ "\n Signature method: " + signatureMethod1663+ "\n Transform: " + transform1664+ "\n Digest method: " + digestMethod1665+ "\n KeyInfoType: " + keyInfo1666+ "\n Content type: " + contentType1667+ "\n Expected failure: " + (expectedFailure ? "yes" : "no")1668+ "\n Expected exception: " + (expectedException == null ?1669"no" : expectedException.getName());16701671try {1672boolean success = test_create_detached_signature0(1673canonicalizationMethod,1674signatureMethod,1675digestMethod,1676transform,1677keyInfo,1678contentType,1679port);16801681if (success && expectedFailure) {1682System.out.println(title);1683System.out.println("Signature validation unexpectedly passed");1684result = false;1685} else if (!success && !expectedFailure) {1686System.out.println(title);1687System.out.println("Signature validation unexpectedly failed");1688result = false;1689} else if (expectedException != null) {1690System.out.println(title);1691System.out.println("Expected " + expectedException1692+ " not thrown");1693result = false;1694}1695} catch (Exception e) {1696if (expectedException == null1697|| !e.getClass().isAssignableFrom(expectedException)) {1698System.out.println(title);1699System.out.println("Unexpected exception: " + e);1700e.printStackTrace(System.out);1701result = false;1702}1703}1704}17051706// Print out as little as possible. This method will be called many times.1707static boolean test_create_detached_signature0(String canonicalizationMethod,1708String signatureMethod, String digestMethod, String transform,1709KeyInfoType keyInfo, Content contentType, int port)1710throws Exception {17111712System.out.print("-S");17131714DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();1715dbf.setNamespaceAware(true);1716dbf.setValidating(false);17171718// Create SignedInfo1719DigestMethod dm = fac.newDigestMethod(digestMethod, null);17201721List transformList = null;1722if (transform != null) {1723TransformParameterSpec params = null;1724switch (transform) {1725case Transform.XPATH:1726params = new XPathFilterParameterSpec("//.");1727break;1728case Transform.XPATH2:1729params = new XPathFilter2ParameterSpec(1730Collections.singletonList(new XPathType("//.",1731XPathType.Filter.INTERSECT)));1732break;1733case Transform.XSLT:1734Element element = dbf.newDocumentBuilder()1735.parse(new ByteArrayInputStream(xslt.getBytes()))1736.getDocumentElement();1737DOMStructure stylesheet = new DOMStructure(element);1738params = new XSLTTransformParameterSpec(stylesheet);1739break;1740}1741transformList = Collections.singletonList(fac.newTransform(1742transform, params));1743}17441745String url = String.format("http://localhost:%d/%s", port, contentType);1746List refs = Collections.singletonList(fac.newReference(url, dm,1747transformList, null, null));17481749CanonicalizationMethod cm = fac.newCanonicalizationMethod(1750canonicalizationMethod, (C14NMethodParameterSpec) null);17511752SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);17531754Key[] pair = getCachedKeys(signatureMethod);1755Key signingKey = pair[0];1756Key validationKey = pair[1];17571758SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);17591760// Create KeyInfo1761KeyInfoFactory kif = fac.getKeyInfoFactory();1762List list = null;1763if (keyInfo == KeyInfoType.KeyValue) {1764if (validationKey instanceof PublicKey) {1765KeyValue kv = kif.newKeyValue((PublicKey) validationKey);1766list = Collections.singletonList(kv);1767}1768} else if (keyInfo == KeyInfoType.x509data) {1769list = Collections.singletonList(1770kif.newX509Data(Collections.singletonList("cn=Test")));1771} else if (keyInfo == KeyInfoType.KeyName) {1772list = Collections.singletonList(kif.newKeyName("Test"));1773} else {1774throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);1775}1776KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;17771778// Create an empty doc for detached signature1779Document doc = dbf.newDocumentBuilder().newDocument();1780DOMSignContext xsc = new DOMSignContext(signingKey, doc);17811782// Generate signature1783XMLSignature signature = fac.newXMLSignature(si, ki);1784signature.sign(xsc);17851786// Save signature1787String signatureString;1788try (StringWriter writer = new StringWriter()) {1789TransformerFactory tf = TransformerFactory.newInstance();1790Transformer trans = tf.newTransformer();1791Node parent = xsc.getParent();1792trans.transform(new DOMSource(parent), new StreamResult(writer));1793signatureString = writer.toString();1794}17951796System.out.print("V");1797try (ByteArrayInputStream bis = new ByteArrayInputStream(1798signatureString.getBytes())) {1799doc = dbf.newDocumentBuilder().parse(bis);1800}18011802NodeList nodeLst = doc.getElementsByTagName("Signature");1803Node node = nodeLst.item(0);1804if (node == null) {1805throw new RuntimeException("Couldn't find Signature element");1806}1807if (!(node instanceof Element)) {1808throw new RuntimeException("Unexpected node type");1809}1810Element sig = (Element) node;18111812// Validate signature1813DOMValidateContext vc = new DOMValidateContext(validationKey, sig);1814vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);1815signature = fac.unmarshalXMLSignature(vc);18161817boolean success = signature.validate(vc);1818if (!success) {1819System.out.print("x");1820if (!secondChanceGranted && OS.contains("SunOS")) {1821removePKCS11Provider();1822// set up the test again1823return test_create_detached_signature0(canonicalizationMethod,1824signatureMethod, digestMethod, transform,1825keyInfo, contentType, port);1826} else {1827return false;1828}1829}18301831success = signature.getSignatureValue().validate(vc);1832if (!success) {1833System.out.print("X");1834return false;1835}18361837return true;1838}18391840/*1841* Helper method for cases where we're running on unpatched1842* solaris systems where PKCS11 native libraries are unpatched1843*/1844private static void removePKCS11Provider() throws Exception {1845secondChanceGranted = true;1846Security.removeProvider("SunPKCS11-Solaris");1847System.out.println("Second chance granted. Provider list: "1848+ Arrays.toString(Security.getProviders()));1849setup();1850}18511852private static Key[] getCachedKeys(String signatureMethod) {1853return cachedKeys.computeIfAbsent(signatureMethod, sm -> {1854try {1855System.out.print("<create keys for " + sm + ">");1856System.out.flush();1857if (sm.contains("#hmac-")) {1858// http://...#hmac-sha1 -> hmac-sha1 -> hmacsha11859String algName = sm1860.substring(sm.indexOf('#') + 1)1861.replace("-", "");1862KeyGenerator kg = KeyGenerator.getInstance(algName);1863Key signingKey = kg.generateKey();1864return new Key[] { signingKey, signingKey};1865} else {1866KeyPairGenerator kpg;1867if (sm.contains("#rsa-")1868|| sm.contains("-rsa-MGF1")) {1869kpg = KeyPairGenerator.getInstance("RSA");1870kpg.initialize(1871sm.contains("#sha512-rsa-MGF1") ? 2048 : 1024);1872} else if (sm.contains("#dsa-")) {1873kpg = KeyPairGenerator.getInstance("DSA");1874kpg.initialize(1024);1875} else if (sm.contains("#ecdsa-")) {1876kpg = KeyPairGenerator.getInstance("EC");1877kpg.initialize(256);1878} else {1879throw new RuntimeException("Unsupported signature algorithm");1880}1881KeyPair kp = kpg.generateKeyPair();1882return new Key[] { kp.getPrivate(), kp.getPublic()};1883}1884} catch (NoSuchAlgorithmException e) {1885throw new AssertionError("Should not happen", e);1886}1887});1888}18891890private static final String DSA_Y =1891"070662842167565771936588335128634396171789331656318483584455493822" +1892"400811200853331373030669235424928346190274044631949560438023934623" +1893"71310375123430985057160";1894private static final String DSA_P =1895"013232376895198612407547930718267435757728527029623408872245156039" +1896"757713029036368719146452186041204237350521785240337048752071462798" +1897"273003935646236777459223";1898private static final String DSA_Q =1899"0857393771208094202104259627990318636601332086981";1900private static final String DSA_G =1901"054216440574364751416096484883257051280474283943804743768346673007" +1902"661082626139005426812890807137245973106730741193551360857959820973" +1903"90670890367185141189796";1904private static final String DSA_X =1905"0527140396812450214498055937934275626078768840117";1906private static final String DSA_2048_Y =1907"15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928";1908private static final String DSA_2048_P =1909"18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359";1910private static final String DSA_2048_Q =1911"19689526866605154788513693571065914024068069442724893395618704484701";1912private static final String DSA_2048_G =1913"2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430";1914private static final String DSA_2048_X =1915"14562787764977288900757387442281559936279834964901963465277698843172";1916private static final String RSA_MOD =1917"010800185049102889923150759252557522305032794699952150943573164381" +1918"936603255999071981574575044810461362008102247767482738822150129277" +1919"490998033971789476107463";1920private static final String RSA_PRIV =1921"016116973584421969795445996229612671947635798429212816611707210835" +1922"915586591340598683996088487065438751488342251960069575392056288063" +1923"6800379454345804879553";1924private static final String RSA_PUB = "065537";1925private static final String RSA_1024_MOD = "098871307553789439961130765" +1926"909423744508062468450669519128736624058048856940468016843888594585" +1927"322862378444314635412341974900625010364163960238734457710620107530" +1928"573945081856371709138380902553309075505688814637544923038853658690" +1929"857672483016239697038853418682988686871489963827000080098971762923" +1930"833614557257607521";1931private static final String RSA_1024_PRIV = "03682574144968491431483287" +1932"297021581096848810374110568017963075809477047466189822987258068867" +1933"704855380407747867998863645890602646601140183818953428006646987710" +1934"237008997971129772408397621801631622129297063463868593083106979716" +1935"204903524890556839550490384015324575598723478554854070823335021842" +1936"210112348400928769";1937private static final String RSA_2048_MOD = "243987087691547796017401146540"1938+ "9844666035826535295137885613771811531602666348704672255163984907599"1939+ "4298308997053582963763109207465354916871136820987101812436158377530"1940+ "6117270010853232249007544652859474372258057062943608962079402484091"1941+ "8121307687901225514249308620012025884376216406019656605767311580224"1942+ "4715304950770504195751384382230005665573033547124060755957932161045"1943+ "7288008201789401237690181537646952377591671113513382933711547044631"1944+ "6055957820531234310030119265612054594720774653570278810236807313332"1945+ "5293876225940483622056721445101719346295263740434720907474414905706"1946+ "086605825077661246082956613711071075569880930102141";1947private static final String RSA_2048_PRIV = "12265063405401593206575340300"1948+ "5824698296458954796982342251774894076489082263237675553422307220014"1949+ "4395010131540855227949365446755185799985229111139387016816011165826"1950+ "5498929552020323994756478872375078784799489891112924298115119573429"1951+ "3677627114115546751555523555375278381312502020990154549150867571006"1952+ "4470674155961982582802981649643127000520693025433874996570667724459"1953+ "3395670697152709457274026580106078581585077146782827694403672461289"1954+ "9143004401242754355097671446183871158504602884373174300123820136505"1955+ "6449932139773607305129273545117363975014750743804523418307647791195"1956+ "6408859873123458434820062206102268853256685162004893";1957private static final String EC_P256_X =1958"335863644451761614592446380116804721648611739647823420286081723541" +1959"6166183710";1960private static final String EC_P256_Y =1961"951559601159729477487064127150143688502130342917782252098602422796" +1962"95457910701";1963private static final String EC_P256_S =1964"425976209773168452211813225517384419928639977904006759709292218082" +1965"7440083936";1966private static final ECParameterSpec EC_P256_PARAMS = initECParams(1967"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",1968"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",1969"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B",1970"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",1971"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",1972"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551",197311974);1975private static final String EC_P384_X =1976"12144058647679082341340699736608428955270957565259459672517275506071643671835484144490620216582303669654008841724053";1977private static final String EC_P384_Y =1978"18287745972107701566600963632634101287058332546756092926848497481238534346489545826483592906634896557151987868614320";1979private static final String EC_P384_S =1980"10307785759830534742680442271492590599236624208247590184679565032330507874096079979152605984203102224450595283943382";1981private static final ECParameterSpec EC_P384_PARAMS = initECParams(1982"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF",1983"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC",1984"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF",1985"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7",1986"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F",1987"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973",198811989);1990private static final String EC_P521_X =1991"4157918188927862838251799402582135611021257663417126086145819679867926857146776190737187582274664373117054717389603317411991660346043842712448912355335343997";1992private static final String EC_P521_Y =1993"4102838062751704796157456866854813794620023146924181568434486703918224542844053923233919899911519054998554969832861957437850996213216829205401947264294066288";1994private static final String EC_P521_S =1995"4857798533181496041050215963883119936300918353498701880968530610687256097257307590162398707429640390843595868713096292822034014722985178583665959048714417342";1996private static final ECParameterSpec EC_P521_PARAMS = initECParams(1997"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",1998"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC",1999"0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00",2000"00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66",2001"011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650",2002"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409",200312004);20052006private static ECParameterSpec initECParams(2007String sfield, String a, String b, String gx, String gy,2008String n, int h) {2009ECField field = new ECFieldFp(bigInt(sfield));2010EllipticCurve curve = new EllipticCurve(field,2011bigInt(a), bigInt(b));2012ECPoint g = new ECPoint(bigInt(gx), bigInt(gy));2013return new ECParameterSpec(curve, g, bigInt(n), h);2014}20152016private static BigInteger bigInt(String s) {2017return new BigInteger(s, 16);2018}2019private static PublicKey getPublicKey(String algo, int keysize)2020throws Exception {2021KeyFactory kf = KeyFactory.getInstance(algo);2022KeySpec kspec;2023if (algo.equalsIgnoreCase("DSA")) {2024if (keysize == 1024) {2025kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),2026new BigInteger(DSA_P),2027new BigInteger(DSA_Q),2028new BigInteger(DSA_G));2029} else if (keysize == 2048) {2030kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y),2031new BigInteger(DSA_2048_P),2032new BigInteger(DSA_2048_Q),2033new BigInteger(DSA_2048_G));2034} else throw new RuntimeException("Unsupported keysize:" + keysize);2035} else if (algo.equalsIgnoreCase("RSA")) {2036if (keysize == 512) {2037kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD),2038new BigInteger(RSA_PUB));2039} else if (keysize == 1024) {2040kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),2041new BigInteger(RSA_PUB));2042} else if (keysize == 2048) {2043kspec = new RSAPublicKeySpec(new BigInteger(RSA_2048_MOD),2044new BigInteger(RSA_PUB));2045} else throw new RuntimeException("Unsupported keysize:" + keysize);2046} else throw new RuntimeException("Unsupported key algorithm " + algo);2047return kf.generatePublic(kspec);2048}20492050private static PublicKey getECPublicKey(String curve) throws Exception {2051KeyFactory kf = KeyFactory.getInstance("EC");2052String x, y;2053ECParameterSpec params;2054switch (curve) {2055case "P256":2056x = EC_P256_X;2057y = EC_P256_Y;2058params = EC_P256_PARAMS;2059break;2060case "P384":2061x = EC_P384_X;2062y = EC_P384_Y;2063params = EC_P384_PARAMS;2064break;2065case "P521":2066x = EC_P521_X;2067y = EC_P521_Y;2068params = EC_P521_PARAMS;2069break;2070default:2071throw new Exception("Unsupported curve: " + curve);2072}2073KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x),2074new BigInteger(y)),2075params);2076return kf.generatePublic(kspec);2077}20782079private static PrivateKey getPrivateKey(String algo, int keysize)2080throws Exception {2081KeyFactory kf = KeyFactory.getInstance(algo);2082KeySpec kspec;2083if (algo.equalsIgnoreCase("DSA")) {2084if (keysize == 1024) {2085kspec = new DSAPrivateKeySpec2086(new BigInteger(DSA_X), new BigInteger(DSA_P),2087new BigInteger(DSA_Q), new BigInteger(DSA_G));2088} else if (keysize == 2048) {2089kspec = new DSAPrivateKeySpec2090(new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P),2091new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));2092} else throw new RuntimeException("Unsupported keysize:" + keysize);2093} else if (algo.equalsIgnoreCase("RSA")) {2094if (keysize == 512) {2095kspec = new RSAPrivateKeySpec2096(new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV));2097} else if (keysize == 1024) {2098kspec = new RSAPrivateKeySpec(new BigInteger(RSA_1024_MOD),2099new BigInteger(RSA_1024_PRIV));2100} else if (keysize == 2048) {2101kspec = new RSAPrivateKeySpec(new BigInteger(RSA_2048_MOD),2102new BigInteger(RSA_2048_PRIV));2103} else throw new RuntimeException("Unsupported key algorithm " + algo);2104} else throw new RuntimeException("Unsupported key algorithm " + algo);2105return kf.generatePrivate(kspec);2106}21072108private static PrivateKey getECPrivateKey(String curve) throws Exception {2109String s;2110ECParameterSpec params;2111switch (curve) {2112case "P256":2113s = EC_P256_S;2114params = EC_P256_PARAMS;2115break;2116case "P384":2117s = EC_P384_S;2118params = EC_P384_PARAMS;2119break;2120case "P521":2121s = EC_P521_S;2122params = EC_P521_PARAMS;2123break;2124default:2125throw new Exception("Unsupported curve: " + curve);2126}2127KeyFactory kf = KeyFactory.getInstance("EC");2128KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);2129return kf.generatePrivate(kspec);2130}21312132private static SecretKey getSecretKey(final byte[] secret) {2133return new SecretKey() {2134public String getFormat() { return "RAW"; }2135public byte[] getEncoded() { return secret; }2136public String getAlgorithm(){ return "SECRET"; }2137};2138}21392140/**2141* This URIDereferencer returns locally cached copies of http content to2142* avoid test failures due to network glitches, etc.2143*/2144private static class HttpURIDereferencer implements URIDereferencer {2145private URIDereferencer defaultUd;21462147HttpURIDereferencer() {2148defaultUd = XMLSignatureFactory.getInstance().getURIDereferencer();2149}21502151public Data dereference(final URIReference ref, XMLCryptoContext ctx)2152throws URIReferenceException {2153String uri = ref.getURI();2154if (uri.equals(STYLESHEET) || uri.equals(STYLESHEET_B64)) {2155try {2156FileInputStream fis = new FileInputStream(new File2157(DATA_DIR, uri.substring(uri.lastIndexOf('/'))));2158return new OctetStreamData(fis,ref.getURI(),ref.getType());2159} catch (Exception e) { throw new URIReferenceException(e); }2160}21612162// fallback on builtin deref2163return defaultUd.dereference(ref, ctx);2164}2165}21662167// local http server2168static class Http implements HttpHandler, AutoCloseable {21692170private final HttpServer server;21712172private Http(HttpServer server) {2173this.server = server;2174}21752176static Http startServer() throws IOException {2177HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);2178return new Http(server);2179}21802181void start() {2182server.createContext("/", this);2183server.start();2184}21852186void stop() {2187server.stop(0);2188}21892190int getPort() {2191return server.getAddress().getPort();2192}21932194@Override2195public void handle(HttpExchange t) throws IOException {2196try {2197String type;2198String path = t.getRequestURI().getPath();2199if (path.startsWith("/")) {2200type = path.substring(1);2201} else {2202type = path;2203}22042205String contentTypeHeader = "";2206byte[] output = new byte[] {};2207int code = 200;2208Content testContentType = Content.valueOf(type);2209switch (testContentType) {2210case Base64:2211contentTypeHeader = "application/octet-stream";2212output = "VGVzdA==".getBytes();2213break;2214case Text:2215contentTypeHeader = "text/plain";2216output = "Text".getBytes();2217break;2218case Xml:2219contentTypeHeader = "application/xml";2220output = "<tag>test</tag>".getBytes();2221break;2222case NotExisitng:2223code = 404;2224break;2225default:2226throw new IOException("Unknown test content type");2227}22282229t.getResponseHeaders().set("Content-Type", contentTypeHeader);2230t.sendResponseHeaders(code, output.length);2231t.getResponseBody().write(output);2232} catch (IOException e) {2233System.out.println("Exception: " + e);2234t.sendResponseHeaders(500, 0);2235}2236t.close();2237}22382239@Override2240public void close() {2241stop();2242}2243}2244}224522462247