You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@santuario.apache.org by co...@apache.org on 2024/05/07 13:27:53 UTC
(santuario-xml-security-java) branch main updated: [SANTUARIO-614] Tests for the EC Brainpool key types (#298)
This is an automated email from the ASF dual-hosted git repository.
coheigea pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/santuario-xml-security-java.git
The following commit(s) were added to refs/heads/main by this push:
new 6b276fb4 [SANTUARIO-614] Tests for the EC Brainpool key types (#298)
6b276fb4 is described below
commit 6b276fb46874e79c68dc9012b3349a1426711f10
Author: jrihtarsic <jr...@gmail.com>
AuthorDate: Tue May 7 15:27:47 2024 +0200
[SANTUARIO-614] Tests for the EC Brainpool key types (#298)
* [SANTUIARIO-614] Tests for the EC Brainpool key types
* Update XMLSignatureBrainpoolTest with XMLSignatureAbstract
add eddsa.jks key creation command to README.txt
* PR: Update instruction how brainpool.p12 is generated using the openssl + fix typo
---------
Co-authored-by: RIHTARSIC Joze <jo...@ext.ec.europa.eu>
---
.../encryption/XMLEncryption11BrainpoolTest.java | 155 ++++++
.../test/dom/encryption/XMLEncryption11Test.java | 476 +------------------
.../encryption/XMLEncryption11TestAbstract.java | 521 +++++++++++++++++++++
.../xml/crypto/dsig/XMLSignatureBrainpoolTest.java | 97 ++++
.../apache/xml/security/samples/input/README.txt | 59 +++
.../xml/security/samples/input/ecbrainpool.p12 | Bin 0 -> 3895 bytes
6 files changed, 835 insertions(+), 473 deletions(-)
diff --git a/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11BrainpoolTest.java b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11BrainpoolTest.java
new file mode 100644
index 00000000..1aa908c2
--- /dev/null
+++ b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11BrainpoolTest.java
@@ -0,0 +1,155 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.xml.security.test.dom.encryption;
+
+import java.io.ByteArrayInputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.Security;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.security.spec.AlgorithmParameterSpec;
+
+import org.w3c.dom.Document;
+
+import org.apache.xml.security.encryption.EncryptedKey;
+import org.apache.xml.security.encryption.params.ConcatKDFParams;
+import org.apache.xml.security.encryption.params.KeyAgreementParameters;
+import org.apache.xml.security.encryption.params.KeyDerivationParameters;
+import org.apache.xml.security.testutils.JDKTestUtils;
+import org.apache.xml.security.utils.EncryptionConstants;
+import org.apache.xml.security.utils.KeyUtils;
+import org.apache.xml.security.utils.XMLUtils;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+/**
+ * This is a test class for the KeyAgreement algorithm with Brainpool curves.
+ * The test uses the AuxiliaryProvider (BouncyCastle) to provide the necessary
+ * algorithms.
+ * <p />
+ * To execute just this tests class run the following command (note the profile):
+ * <code>mvn test -Dtest=XMLEncryption11BrainpoolTest -P bouncycastle</code>
+ * or to test it during the build start the project with the profile "bouncycastle"
+ * <code>mvn clean install -P bouncycastle</code>
+ */
+class XMLEncryption11BrainpoolTest extends XMLEncryption11TestAbstract{
+ protected static final System.Logger LOG = System.getLogger(XMLEncryption11BrainpoolTest.class.getName());
+
+ @BeforeAll
+ static void initProvider() {
+ Assumptions.assumeTrue(JDKTestUtils.getAuxiliaryProvider() != null, "BouncyCastle is required for this test");
+ Assumptions.assumeFalse("IBM Corporation".equals(System.getProperty("java.vendor")), "Skip for IBM JDK" );
+ Security.insertProviderAt(JDKTestUtils.getAuxiliaryProvider(), 1);
+ }
+
+ @AfterAll
+ static void removeProvider() {
+ if (JDKTestUtils.getAuxiliaryProvider()!=null) {
+ Security.removeProvider(JDKTestUtils.getAuxiliaryProvider().getName());
+ }
+ }
+
+ /**
+ * The KeyAgreement test cases from the W3C test suite using bytearray as input.
+ *
+ * <a href="https://www.w3.org/2008/xmlsec/Drafts/xmlenc-core-11/test-cases/#sec-KeyAgreement">
+ * xmlenc-core-11 test-cases</a>
+ */
+ @ParameterizedTest
+ @CsvSource({
+ "1. brainpoolP256r1, binary-data.hex, ecbrainpool.p12, PKCS12, security, brainpoolP256r1," +
+ " http://www.w3.org/2001/04/xmlenc#kw-aes128, http://www.w3.org/2009/xmlenc11#aes128-gcm," +
+ " http://www.w3.org/2001/04/xmlenc#sha256",
+ "2. brainpoolP384r1, binary-data.hex, ecbrainpool.p12, PKCS12, security, brainpoolP384r1," +
+ " http://www.w3.org/2001/04/xmlenc#kw-aes128, http://www.w3.org/2009/xmlenc11#aes128-gcm," +
+ " http://www.w3.org/2001/04/xmlenc#sha256",
+ "3. brainpoolP512r1, binary-data.hex, ecbrainpool.p12, PKCS12, security, brainpoolP512r1," +
+ " http://www.w3.org/2001/04/xmlenc#kw-aes128, http://www.w3.org/2009/xmlenc11#aes128-gcm," +
+ " http://www.w3.org/2001/04/xmlenc#sha256",
+ })
+ void testAgreementKeyEncryptDecryptDataWithBrainpool(String w3cTag,
+ String resourceHexFileName,
+ String keystoreFile, String keystoreType,
+ String passwd, String alias,
+ String keyWrapAlgorithm,
+ String encryptionAlgorithm,
+ String kdfAlgorithm) throws Exception {
+ Assumptions.assumeTrue(haveISOPadding,
+ "Skipping testAgreementKey ["+w3cTag+"] as necessary crypto algorithms are not available");
+
+ // Load the keystore
+ String resourceFolder = "/org/apache/xml/security/samples/input/";
+ KeyStore keyStore = loadKeyStoreFromResource(resourceFolder, keystoreFile, passwd, keystoreType);
+ Certificate cert = keyStore.getCertificate(alias);
+
+ KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
+ keyStore.getEntry(alias, new KeyStore.PasswordProtection(passwd.toCharArray()));
+ PrivateKey ecKey = pkEntry.getPrivateKey();
+
+ // Perform encryption
+ byte[] testData = hexFileContentByteArray(resourceHexFileName);
+ // create empty document for EncryptedKey
+ Document doc = DEFAULT_DOCUMENT_BUILDER_FACTORY.newDocumentBuilder().newDocument();
+
+ Key sessionKey = getSessionKey(encryptionAlgorithm);
+
+ int keyBitLen = KeyUtils.getAESKeyBitSizeForWrapAlgorithm(keyWrapAlgorithm);
+ KeyDerivationParameters keyDerivationParameter = new ConcatKDFParams(keyBitLen, kdfAlgorithm);
+ AlgorithmParameterSpec parameterSpec = new KeyAgreementParameters(
+ KeyAgreementParameters.ActorType.ORIGINATOR,
+ EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES,
+ keyDerivationParameter);
+
+ EncryptedKey encryptedKey =
+ createEncryptedKey(
+ doc,
+ (X509Certificate)cert,
+ sessionKey,
+ keyWrapAlgorithm,
+ parameterSpec, null);
+
+ doc = encryptData(
+ doc,
+ encryptedKey,
+ sessionKey,
+ encryptionAlgorithm,
+ new ByteArrayInputStream(testData)
+ );
+
+ if (LOG.isLoggable(System.Logger.Level.DEBUG)) {
+ Files.write(Paths.get("target","test-enc-"+w3cTag+".xml"), toString(doc.getFirstChild()).getBytes());
+ XMLUtils.outputDOM(doc.getFirstChild(), System.out);
+ }
+ // Perform decryption
+ byte[] result = decryptData(doc, ecKey, (X509Certificate)cert);
+
+ assertNotNull(result);
+ assertArrayEquals(testData, result);
+ }
+}
diff --git a/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11Test.java b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11Test.java
index 08175d22..733dbdd4 100644
--- a/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11Test.java
+++ b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11Test.java
@@ -19,48 +19,21 @@
package org.apache.xml.security.test.dom.encryption;
import java.io.*;
-import java.lang.System.Logger;
import java.lang.System.Logger.Level;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Key;
import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.crypto.Cipher;
-import javax.crypto.KeyGenerator;
-import javax.crypto.NoSuchPaddingException;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpressionException;
-import javax.xml.xpath.XPathFactory;
-
-import org.apache.xml.security.algorithms.JCEMapper;
-import org.apache.xml.security.c14n.Canonicalizer;
-import org.apache.xml.security.encryption.AgreementMethod;
-import org.apache.xml.security.encryption.EncryptedData;
+
import org.apache.xml.security.encryption.EncryptedKey;
-import org.apache.xml.security.encryption.XMLCipher;
-import org.apache.xml.security.encryption.keys.KeyInfoEnc;
import org.apache.xml.security.encryption.params.ConcatKDFParams;
import org.apache.xml.security.encryption.params.KeyAgreementParameters;
import org.apache.xml.security.encryption.params.KeyDerivationParameters;
-import org.apache.xml.security.keys.KeyInfo;
-import org.apache.xml.security.keys.content.X509Data;
-import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
-import org.apache.xml.security.parser.XMLParserException;
-import org.apache.xml.security.test.dom.DSNamespaceContext;
import org.apache.xml.security.utils.Constants;
import org.apache.xml.security.utils.EncryptionConstants;
import org.apache.xml.security.utils.KeyUtils;
@@ -70,8 +43,6 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
import static org.apache.xml.security.test.XmlSecTestEnvironment.resolveFile;
import static org.junit.jupiter.api.Assertions.*;
@@ -85,57 +56,9 @@ import static org.junit.jupiter.api.Assumptions.assumeFalse;
*
* Note: I had to convert the given .p12 file into a .jks as it could not be loaded with KeyStore.
*/
-class XMLEncryption11Test {
-
- private static final DocumentBuilderFactory DEFAULT_DOCUMENT_BUILDER_FACTORY;
- static {
- DEFAULT_DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
- DEFAULT_DOCUMENT_BUILDER_FACTORY.setNamespaceAware(true);
- }
- private static final String RESOURCE_FOLDER = "/org/w3c/www/interop/xmlenc-core-11/";
-
- private static String cardNumber;
- private static int nodeCount = 0;
- private boolean haveISOPadding;
- private final boolean isIBMJdK = System.getProperty("java.vendor").contains("IBM");
-
- private static final Logger LOG = System.getLogger(XMLEncryption11Test.class.getName());
-
-
- /**
- * Constructor XMLEncryption11Test
- */
- public XMLEncryption11Test() throws Exception {
+class XMLEncryption11Test extends XMLEncryption11TestAbstract {
+ protected static final System.Logger LOG = System.getLogger(XMLEncryption11Test.class.getName());
- // Create the comparison strings
- File f = resolveFile("src/test/resources/org/w3c/www/interop/xmlenc-core-11/plaintext.xml");
- Document doc = XMLUtils.read(f, false);
-
- cardNumber = retrieveCCNumber(doc);
-
- // Count the nodes in the document as a secondary test
- nodeCount = countNodes(doc);
-
- // Initialise the library
- org.apache.xml.security.Init.init();
-
- // Check what algorithms are available
-
- haveISOPadding = false;
- String algorithmId = JCEMapper.translateURItoJCEID(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
-
- if (algorithmId != null) {
- try {
- if (Cipher.getInstance(algorithmId) != null) {
- haveISOPadding = true;
- }
- } catch (NoSuchAlgorithmException nsae) {
- //
- } catch (NoSuchPaddingException nspe) {
- //
- }
- }
- }
/**
* rsa-oaep-mgf1p, Digest:SHA256, MGF:SHA1, PSource: None
@@ -746,397 +669,4 @@ class XMLEncryption11Test {
assertNotNull(result);
assertArrayEquals(testData, result);
}
-
- private KeyStore loadKeyStore(File keystore)
- throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
- KeyStore keyStore = KeyStore.getInstance(getKeystoreTypeForFileName(keystore.getName()));
- try (FileInputStream inputStream = new FileInputStream(keystore)) {
- keyStore.load(inputStream, "passwd".toCharArray());
- }
- return keyStore;
- }
-
- private KeyStore loadKeyStoreFromResource(String filename, String passwd, String keystoreType)
- throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
-
- KeyStore keyStore = KeyStore.getInstance(keystoreType);
- try ( InputStream keystoreIS = getResourceInputStream(filename);) {
- keyStore.load(keystoreIS, passwd!=null?passwd.toCharArray():null);
- }
- return keyStore;
- }
-
- private Document loadDocumentFromResource(String resourceName)
- throws IOException, XMLParserException {
-
- try (InputStream dataXMLInputStream = getResourceInputStream(resourceName)){
- return XMLUtils.read(dataXMLInputStream, false);
- }
- }
-
- private String getKeystoreTypeForFileName(String filename){
- return filename.toLowerCase().endsWith(".p12") ? "PKCS12" : "JKS";
- }
-
- /**
- * Method decryptElement
- *
- * Take a key, encryption type and a file, find an encrypted element
- * decrypt it and return the resulting document
- *
- * @param decKey The Key to use for decryption
- * @param encCert The certificate used to encrypt the key
- */
- private Document decryptElement(File file, Key decKey, X509Certificate encCert) throws Exception {
- // Parse the document in question
- Document doc;
- try (FileInputStream inputStream = new FileInputStream(file)) {
- doc = XMLUtils.read(inputStream, false);
- }
- return decryptElement(doc, decKey, encCert);
- }
-
- /**
- * Method decryptElement
- *
- * Take a key, encryption type and a document, find an encrypted element
- * decrypt it and return the resulting document
- *
- * @param doc the XML document wrrapping the encrypted data
- * @param decKey The Key to use for decryption
- * @param encCert The certificate used to encrypt the key
- */
- private Document decryptElement(Document doc, Key decKey, X509Certificate encCert) throws Exception {
- // Create the XMLCipher element
- XMLCipher cipher = XMLCipher.getInstance();
-
- // Need to pre-load the Encrypted Data so we can get the key info
- Element ee = (Element) doc.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData").item(0);
- cipher.init(XMLCipher.DECRYPT_MODE, null);
- EncryptedData encryptedData = cipher.loadEncryptedData(doc, ee);
-
- KeyInfo ki = encryptedData.getKeyInfo();
- EncryptedKey encryptedKey = ki.itemEncryptedKey(0);
- KeyInfoEnc kiek = (KeyInfoEnc)encryptedKey.getKeyInfo();
- if (kiek.containsAgreementMethod()){
- AgreementMethod agreementMethod = kiek.itemAgreementMethod(0);
- kiek = agreementMethod.getRecipientKeyInfo();
- }
- X509Data certData = kiek.itemX509Data(0);
- XMLX509Certificate xcert = certData.itemCertificate(0);
- X509Certificate cert = xcert.getX509Certificate();
- assertEquals(encCert, cert);
-
- XMLCipher cipher2 = XMLCipher.getInstance();
- cipher2.init(XMLCipher.UNWRAP_MODE, decKey);
- Key key = cipher2.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
-
- cipher.init(XMLCipher.DECRYPT_MODE, key);
- Document dd = cipher.doFinal(doc, ee);
-
- return dd;
- }
-
- /**
- * Method decryptElement
- *
- * Take a key, encryption type and a document, find an encrypted element
- * decrypt it and return the resulting document
- *
- * @param doc the XML document wrrapping the encrypted data
- * @param decKey The Key to use for decryption
- * @param rsaCert The certificate used to encrypt the key
- *
- */
- private byte[] decryptData(Document doc, Key decKey, X509Certificate rsaCert) throws Exception {
- // Create the XMLCipher element
- XMLCipher cipher = XMLCipher.getInstance();
-
- // Need to pre-load the Encrypted Data so we can get the key info
- Element ee = (Element) doc.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData").item(0);
- cipher.init(XMLCipher.DECRYPT_MODE, null);
- EncryptedData encryptedData = cipher.loadEncryptedData(doc, ee);
-
- KeyInfo ki = encryptedData.getKeyInfo();
- EncryptedKey encryptedKey = ki.itemEncryptedKey(0);
- KeyInfoEnc kiek = (KeyInfoEnc)encryptedKey.getKeyInfo();
- if (kiek.containsAgreementMethod()){
- AgreementMethod agreementMethod = kiek.itemAgreementMethod(0);
- kiek = agreementMethod.getRecipientKeyInfo();
- }
- X509Data certData = kiek.itemX509Data(0);
- XMLX509Certificate xcert = certData.itemCertificate(0);
- X509Certificate cert = xcert.getX509Certificate();
- assertEquals(rsaCert, cert);
-
- XMLCipher cipher2 = XMLCipher.getInstance();
- cipher2.init(XMLCipher.UNWRAP_MODE, decKey);
- Key key = cipher2.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
-
- cipher.init(XMLCipher.DECRYPT_MODE, key);
- return cipher.decryptToByteArray(ee);
- }
-
- /**
- * Create an EncryptedKey object using the given parameters.
- */
- private EncryptedKey createEncryptedKey(
- Document doc,
- X509Certificate rsaCert,
- Key sessionKey,
- String encryptionMethod,
- String digestMethod,
- String mgfAlgorithm,
- byte[] oaepParams
- ) throws Exception {
- return createEncryptedKey(doc, rsaCert, sessionKey, encryptionMethod,
- digestMethod, mgfAlgorithm, oaepParams, null);
- }
-
- private EncryptedKey createEncryptedKey(
- Document doc,
- X509Certificate rsaCert,
- Key sessionKey,
- String encryptionMethod,
- String digestMethod,
- String mgfAlgorithm,
- byte[] oaepParams,
- SecureRandom random
- ) throws Exception {
- // Create the XMLCipher element
- XMLCipher cipher = XMLCipher.getInstance(encryptionMethod, null, digestMethod);
-
- cipher.init(XMLCipher.WRAP_MODE, rsaCert.getPublicKey());
-
- EncryptedKey encryptedKey = cipher.encryptKey(doc, sessionKey, mgfAlgorithm, oaepParams, random);
-
- KeyInfo builderKeyInfo = encryptedKey.getKeyInfo();
- if (builderKeyInfo == null) {
- builderKeyInfo = new KeyInfo(doc);
- encryptedKey.setKeyInfo(builderKeyInfo);
- }
-
- X509Data x509Data = new X509Data(doc);
- x509Data.addCertificate(rsaCert);
- builderKeyInfo.add(x509Data);
-
- return encryptedKey;
- }
-
- private EncryptedKey createEncryptedKey(
- Document doc,
- X509Certificate cert,
- Key sessionKey,
- String encryptionMethod,
- AlgorithmParameterSpec params,
- SecureRandom random
- ) throws Exception {
- // Create the XMLCipher element
- XMLCipher cipher = XMLCipher.getInstance(encryptionMethod, null, null);
-
- cipher.init(XMLCipher.WRAP_MODE, cert.getPublicKey());
-
- EncryptedKey encryptedKey = cipher.encryptKey(doc, sessionKey, params, random);
-
- KeyInfo builderKeyInfo = encryptedKey.getKeyInfo();
- if (builderKeyInfo == null) {
- builderKeyInfo = new KeyInfoEnc(doc);
- encryptedKey.setKeyInfo(builderKeyInfo);
- }
-
- X509Data x509Data = new X509Data(doc);
- x509Data.addCertificate(cert);
- if (builderKeyInfo instanceof KeyInfoEnc
- && ((KeyInfoEnc)builderKeyInfo).lengthAgreementMethod()>0) {
- AgreementMethod agreementMethod = ((KeyInfoEnc)builderKeyInfo).itemAgreementMethod(0);
- agreementMethod.getRecipientKeyInfo().add(x509Data);
- } else {
- builderKeyInfo.add(x509Data);
- }
- return encryptedKey;
- }
-
- /**
- * Generate a session key using the given algorithm
- */
- private Key getSessionKey(String encryptionMethod) throws Exception {
- // Generate a session key
- KeyGenerator keyGen = KeyGenerator.getInstance("AES");
- if (encryptionMethod.contains("128")) {
- keyGen.init(128);
- } else if (encryptionMethod.contains("192")) {
- keyGen.init(192);
- } else if (encryptionMethod.contains("256")) {
- keyGen.init(256);
- }
- return keyGen.generateKey();
- }
-
- /**
- * Encrypt a Document using the given parameters.
- */
- private Document encryptDocument(
- Document doc,
- EncryptedKey encryptedKey,
- Key sessionKey,
- String encryptionMethod
- ) throws Exception {
- // Create the XMLCipher element
- XMLCipher cipher = XMLCipher.getInstance(encryptionMethod);
-
- cipher.init(XMLCipher.ENCRYPT_MODE, sessionKey);
- EncryptedData builder = cipher.getEncryptedData();
-
- KeyInfo builderKeyInfo = builder.getKeyInfo();
- if (builderKeyInfo == null) {
- builderKeyInfo = new KeyInfo(doc);
- builder.setKeyInfo(builderKeyInfo);
- }
-
- builderKeyInfo.add(encryptedKey);
-
- return cipher.doFinal(doc, doc.getDocumentElement());
- }
-
-
- /**
- * Encrypt a Document using the given parameters.
- */
- private Document encryptData(
- Document doc,
- EncryptedKey encryptedKey,
- Key sessionKey,
- String encryptionMethod,
- InputStream dataToEncrypt
- ) throws Exception {
- // Create the XMLCipher element
- XMLCipher cipher = XMLCipher.getInstance(encryptionMethod);
-
- cipher.init(XMLCipher.ENCRYPT_MODE, sessionKey);
- EncryptedData builder = cipher.getEncryptedData();
-
- KeyInfo builderKeyInfo = builder.getKeyInfo();
- if (builderKeyInfo == null) {
- builderKeyInfo = new KeyInfo(doc);
- builder.setKeyInfo(builderKeyInfo);
- }
-
- builderKeyInfo.add(encryptedKey);
-
- EncryptedData endData = cipher.encryptData(doc, null, dataToEncrypt);
- Element encDataElement = cipher.martial(endData);
- doc.appendChild(encDataElement);
- return doc;
- }
-
- /**
- * Method countNodes
- *
- * Recursively count the number of nodes in the document
- *
- * @param n Node to count beneath
- */
- private static int countNodes(Node n) {
-
- if (n == null) {
- return 0; // Paranoia
- }
-
- int count = 1; // Always count myself
- Node c = n.getFirstChild();
-
- while (c != null) {
- count += countNodes(c);
- c = c.getNextSibling();
- }
-
- return count;
- }
-
- /**
- * Method retrieveCCNumber
- *
- * Retrieve the credit card number from the payment info document
- *
- * @param doc The document to retrieve the card number from
- * @return The retrieved credit card number
- * @throws XPathExpressionException
- */
- private static String retrieveCCNumber(Document doc)
- throws javax.xml.transform.TransformerException,
- XPathExpressionException {
-
- XPathFactory xpf = XPathFactory.newInstance();
- XPath xpath = xpf.newXPath();
- Map<String, String> namespace = new HashMap<>();
- namespace.put("x", "urn:example:po");
- DSNamespaceContext context = new DSNamespaceContext(namespace);
- xpath.setNamespaceContext(context);
-
- String expression = "//x:Number/text()";
- Node ccnumElt =
- (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
-
- if (ccnumElt != null) {
- return ccnumElt.getNodeValue();
- }
-
- return null;
- }
-
- /*
- * Check we have retrieved a Credit Card number and that it is OK
- * Check that the document has the correct number of nodes
- */
- private void checkDecryptedDoc(Document d, boolean doNodeCheck) throws Exception {
-
- String cc = retrieveCCNumber(d);
- LOG.log(Level.DEBUG, "Retrieved Credit Card : " + cc);
- assertEquals(cardNumber, cc);
-
- // Test cc numbers
- if (doNodeCheck) {
- int myNodeCount = countNodes(d);
-
- assertTrue(
- myNodeCount > 0 && myNodeCount == nodeCount, "Node count mismatches"
- );
- }
- }
-
- public static byte[] hexFileContentByteArray(String fileName) throws IOException {
- byte[] data;
- try (InputStream is = getResourceInputStream(fileName)) {
- int l = is.available() / 2;
- data = new byte[l];
- byte[] charByte = new byte[2];
- for (int i = 0; i < l; i++) {
- is.read(charByte);
- data[i] = (byte) ((Character.digit(charByte[0], 16) << 4)
- + Character.digit(charByte[1], 16));
- }
- }
- return data;
- }
-
- /**
- * Method returns a resource input stream object from resources folder '/org/w3c/www/interop/xmlenc-core-11/'
- * @param resourceName name of the resource file
- * @return InputStream object or null if resource not found
- */
- public static InputStream getResourceInputStream(String resourceName) {
- return XMLEncryption11Test.class.getResourceAsStream(RESOURCE_FOLDER + resourceName);
- }
-
-
- private String toString (Node n) throws Exception {
- try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
- Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
-
- c14n.canonicalizeSubtree(n, baos);
- baos.flush();
-
- return baos.toString(StandardCharsets.UTF_8);
- }
- }
}
diff --git a/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11TestAbstract.java b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11TestAbstract.java
new file mode 100644
index 00000000..77544f06
--- /dev/null
+++ b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLEncryption11TestAbstract.java
@@ -0,0 +1,521 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.xml.security.test.dom.encryption;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.NoSuchPaddingException;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.TransformerException;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import java.io.*;
+import java.nio.charset.StandardCharsets;
+import java.security.*;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.security.spec.AlgorithmParameterSpec;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import org.apache.xml.security.algorithms.JCEMapper;
+import org.apache.xml.security.c14n.Canonicalizer;
+import org.apache.xml.security.encryption.AgreementMethod;
+import org.apache.xml.security.encryption.EncryptedData;
+import org.apache.xml.security.encryption.EncryptedKey;
+import org.apache.xml.security.encryption.XMLCipher;
+import org.apache.xml.security.encryption.keys.KeyInfoEnc;
+import org.apache.xml.security.keys.KeyInfo;
+import org.apache.xml.security.keys.content.X509Data;
+import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
+import org.apache.xml.security.parser.XMLParserException;
+import org.apache.xml.security.test.dom.DSNamespaceContext;
+import org.apache.xml.security.utils.EncryptionConstants;
+import org.apache.xml.security.utils.XMLUtils;
+import org.junit.jupiter.api.BeforeEach;
+
+import static org.apache.xml.security.test.XmlSecTestEnvironment.resolveFile;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * This is abstract class for with common methods for to test vectors
+ * associated with the W3C XML Encryption 1.1 specification:
+ * <p>
+ * <a href="http://www.w3.org/2008/xmlsec/Drafts/xmlenc-core-11/test-cases/">
+ * xmlenc-core-11 test-cases</a>
+ * <p>
+ * The abstract class method can also be used with newer cryptographic algorithms used in
+ * the same XML manner as the older algorithms specified in the
+ * "W3C XML Encryption 1.1" specification
+ */
+public abstract class XMLEncryption11TestAbstract {
+
+ protected static final DocumentBuilderFactory DEFAULT_DOCUMENT_BUILDER_FACTORY;
+ private static final System.Logger LOG = System.getLogger(XMLEncryption11TestAbstract.class.getName());
+ private static final String RESOURCE_FOLDER = "/org/w3c/www/interop/xmlenc-core-11/";
+ private static String cardNumber;
+ private static int nodeCount = 0;
+
+ static {
+ DEFAULT_DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
+ DEFAULT_DOCUMENT_BUILDER_FACTORY.setNamespaceAware(true);
+ }
+
+ protected final boolean isIBMJdK = System.getProperty("java.vendor").contains("IBM");
+ protected boolean haveISOPadding;
+
+
+ @BeforeEach
+ public void beforeEach() throws XMLParserException, IOException, XPathExpressionException, TransformerException {
+ // Create the comparison strings
+ File f = resolveFile("src/test/resources/org/w3c/www/interop/xmlenc-core-11/plaintext.xml");
+ Document doc = XMLUtils.read(f, false);
+
+ cardNumber = retrieveCCNumber(doc);
+
+ // Count the nodes in the document as a secondary test
+ nodeCount = countNodes(doc);
+
+ // Initialise the library
+ org.apache.xml.security.Init.init();
+
+ // Check what algorithms are available
+
+ haveISOPadding = false;
+ String algorithmId = JCEMapper.translateURItoJCEID(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
+
+ if (algorithmId != null) {
+ try {
+ if (Cipher.getInstance(algorithmId) != null) {
+ haveISOPadding = true;
+ }
+ } catch (NoSuchAlgorithmException nsae) {
+ //
+ } catch (NoSuchPaddingException nspe) {
+ //
+ }
+ }
+ }
+
+ /**
+ * Method countNodes
+ * <p>
+ * Recursively count the number of nodes in the document
+ *
+ * @param n Node to count beneath
+ */
+ protected static int countNodes(Node n) {
+
+ if (n == null) {
+ return 0; // Paranoia
+ }
+
+ int count = 1; // Always count myself
+ Node c = n.getFirstChild();
+
+ while (c != null) {
+ count += XMLEncryption11TestAbstract.countNodes(c);
+ c = c.getNextSibling();
+ }
+
+ return count;
+ }
+
+ /**
+ * Method retrieveCCNumber
+ * <p>
+ * Retrieve the credit card number from the payment info document
+ *
+ * @param doc The document to retrieve the card number from
+ * @return The retrieved credit card number
+ * @throws XPathExpressionException
+ */
+ protected static String retrieveCCNumber(Document doc)
+ throws XPathExpressionException {
+
+ XPathFactory xpf = XPathFactory.newInstance();
+ XPath xpath = xpf.newXPath();
+ Map<String, String> namespace = new HashMap<>();
+ namespace.put("x", "urn:example:po");
+ DSNamespaceContext context = new DSNamespaceContext(namespace);
+ xpath.setNamespaceContext(context);
+
+ String expression = "//x:Number/text()";
+ Node ccnumElt =
+ (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
+
+ if (ccnumElt != null) {
+ return ccnumElt.getNodeValue();
+ }
+
+ return null;
+ }
+
+ public static byte[] hexFileContentByteArray(String fileName) throws IOException {
+ byte[] data;
+ try (InputStream is = XMLEncryption11TestAbstract.getResourceInputStream(fileName)) {
+ int l = is.available() / 2;
+ data = new byte[l];
+ byte[] charByte = new byte[2];
+ for (int i = 0; i < l; i++) {
+ is.read(charByte);
+ data[i] = (byte) ((Character.digit(charByte[0], 16) << 4)
+ + Character.digit(charByte[1], 16));
+ }
+ }
+ return data;
+ }
+
+ /**
+ * Method returns a resource input stream object from resources folder '/org/w3c/www/interop/xmlenc-core-11/'
+ *
+ * @param resourceName name of the resource file
+ * @return InputStream object or null if resource not found
+ */
+ public static InputStream getResourceInputStream(String resourceName) {
+ return XMLEncryption11TestAbstract.getResourceInputStream(RESOURCE_FOLDER, resourceName);
+ }
+
+ public static InputStream getResourceInputStream(String resourceFolder, String resourceName) {
+ return XMLEncryption11Test.class.getResourceAsStream(resourceFolder + resourceName);
+ }
+
+ protected KeyStore loadKeyStore(File keystore)
+ throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
+ KeyStore keyStore = KeyStore.getInstance(getKeystoreTypeForFileName(keystore.getName()));
+ try (FileInputStream inputStream = new FileInputStream(keystore)) {
+ keyStore.load(inputStream, "passwd".toCharArray());
+ }
+ return keyStore;
+ }
+
+ protected KeyStore loadKeyStoreFromResource(String filename, String passwd, String keystoreType)
+ throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
+
+ return loadKeyStoreFromResource(RESOURCE_FOLDER, filename, passwd, keystoreType);
+ }
+
+ protected KeyStore loadKeyStoreFromResource(String resourceFolder, String filename, String passwd, String
+ keystoreType)
+ throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
+
+ KeyStore keyStore = KeyStore.getInstance(keystoreType);
+ try (InputStream keystoreIS = XMLEncryption11TestAbstract.getResourceInputStream(resourceFolder, filename)) {
+ keyStore.load(keystoreIS, passwd != null ? passwd.toCharArray() : null);
+ }
+ return keyStore;
+ }
+
+ protected Document loadDocumentFromResource(String resourceName)
+ throws IOException, XMLParserException {
+
+ try (InputStream dataXMLInputStream = XMLEncryption11TestAbstract.getResourceInputStream(resourceName)) {
+ return XMLUtils.read(dataXMLInputStream, false);
+ }
+ }
+
+ private String getKeystoreTypeForFileName(String filename) {
+ return filename.toLowerCase().endsWith(".p12") ? "PKCS12" : "JKS";
+ }
+
+ /**
+ * Method decryptElement
+ * <p>
+ * Take a key, encryption type and a file, find an encrypted element
+ * decrypt it and return the resulting document
+ *
+ * @param decKey The Key to use for decryption
+ * @param encCert The certificate used to encrypt the key
+ */
+ protected Document decryptElement(File file, Key decKey, X509Certificate encCert) throws Exception {
+ // Parse the document in question
+ Document doc;
+ try (FileInputStream inputStream = new FileInputStream(file)) {
+ doc = XMLUtils.read(inputStream, false);
+ }
+ return decryptElement(doc, decKey, encCert);
+ }
+
+ /**
+ * Method decryptElement
+ * <p>
+ * Take a key, encryption type and a document, find an encrypted element
+ * decrypt it and return the resulting document
+ *
+ * @param doc the XML document wrrapping the encrypted data
+ * @param decKey The Key to use for decryption
+ * @param encCert The certificate used to encrypt the key
+ */
+ protected Document decryptElement(Document doc, Key decKey, X509Certificate encCert) throws Exception {
+ // Create the XMLCipher element
+ XMLCipher cipher = XMLCipher.getInstance();
+
+ // Need to pre-load the Encrypted Data so we can get the key info
+ Element ee = (Element) doc.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData").item(0);
+ cipher.init(XMLCipher.DECRYPT_MODE, null);
+ EncryptedData encryptedData = cipher.loadEncryptedData(doc, ee);
+
+ KeyInfo ki = encryptedData.getKeyInfo();
+ EncryptedKey encryptedKey = ki.itemEncryptedKey(0);
+ KeyInfoEnc kiek = (KeyInfoEnc) encryptedKey.getKeyInfo();
+ if (kiek.containsAgreementMethod()) {
+ AgreementMethod agreementMethod = kiek.itemAgreementMethod(0);
+ kiek = agreementMethod.getRecipientKeyInfo();
+ }
+ X509Data certData = kiek.itemX509Data(0);
+ XMLX509Certificate xcert = certData.itemCertificate(0);
+ X509Certificate cert = xcert.getX509Certificate();
+ assertEquals(encCert, cert);
+
+ XMLCipher cipher2 = XMLCipher.getInstance();
+ cipher2.init(XMLCipher.UNWRAP_MODE, decKey);
+ Key key = cipher2.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
+
+ cipher.init(XMLCipher.DECRYPT_MODE, key);
+ return cipher.doFinal(doc, ee);
+ }
+
+ /**
+ * Method decryptElement
+ * <p>
+ * Take a key, encryption type and a document, find an encrypted element
+ * decrypt it and return the resulting document
+ *
+ * @param doc the XML document wrrapping the encrypted data
+ * @param decKey The Key to use for decryption
+ * @param rsaCert The certificate used to encrypt the key
+ */
+ protected byte[] decryptData(Document doc, Key decKey, X509Certificate rsaCert) throws Exception {
+ // Create the XMLCipher element
+ XMLCipher cipher = XMLCipher.getInstance();
+
+ // Need to pre-load the Encrypted Data so we can get the key info
+ Element ee = (Element) doc.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData").item(0);
+ cipher.init(XMLCipher.DECRYPT_MODE, null);
+ EncryptedData encryptedData = cipher.loadEncryptedData(doc, ee);
+
+ KeyInfo ki = encryptedData.getKeyInfo();
+ EncryptedKey encryptedKey = ki.itemEncryptedKey(0);
+ KeyInfoEnc kiek = (KeyInfoEnc) encryptedKey.getKeyInfo();
+ if (kiek.containsAgreementMethod()) {
+ AgreementMethod agreementMethod = kiek.itemAgreementMethod(0);
+ kiek = agreementMethod.getRecipientKeyInfo();
+ }
+ X509Data certData = kiek.itemX509Data(0);
+ XMLX509Certificate xcert = certData.itemCertificate(0);
+ X509Certificate cert = xcert.getX509Certificate();
+ assertEquals(rsaCert, cert);
+
+ XMLCipher cipher2 = XMLCipher.getInstance();
+ cipher2.init(XMLCipher.UNWRAP_MODE, decKey);
+ Key key = cipher2.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
+
+ cipher.init(XMLCipher.DECRYPT_MODE, key);
+ return cipher.decryptToByteArray(ee);
+ }
+
+ /**
+ * Create an EncryptedKey object using the given parameters.
+ */
+ protected EncryptedKey createEncryptedKey(
+ Document doc,
+ X509Certificate rsaCert,
+ Key sessionKey,
+ String encryptionMethod,
+ String digestMethod,
+ String mgfAlgorithm,
+ byte[] oaepParams
+ ) throws Exception {
+ return createEncryptedKey(doc, rsaCert, sessionKey, encryptionMethod,
+ digestMethod, mgfAlgorithm, oaepParams, null);
+ }
+
+ protected EncryptedKey createEncryptedKey(
+ Document doc,
+ X509Certificate rsaCert,
+ Key sessionKey,
+ String encryptionMethod,
+ String digestMethod,
+ String mgfAlgorithm,
+ byte[] oaepParams,
+ SecureRandom random
+ ) throws Exception {
+ // Create the XMLCipher element
+ XMLCipher cipher = XMLCipher.getInstance(encryptionMethod, null, digestMethod);
+
+ cipher.init(XMLCipher.WRAP_MODE, rsaCert.getPublicKey());
+
+ EncryptedKey encryptedKey = cipher.encryptKey(doc, sessionKey, mgfAlgorithm, oaepParams, random);
+
+ KeyInfo builderKeyInfo = encryptedKey.getKeyInfo();
+ if (builderKeyInfo == null) {
+ builderKeyInfo = new KeyInfo(doc);
+ encryptedKey.setKeyInfo(builderKeyInfo);
+ }
+
+ X509Data x509Data = new X509Data(doc);
+ x509Data.addCertificate(rsaCert);
+ builderKeyInfo.add(x509Data);
+
+ return encryptedKey;
+ }
+
+ protected EncryptedKey createEncryptedKey(
+ Document doc,
+ X509Certificate cert,
+ Key sessionKey,
+ String encryptionMethod,
+ AlgorithmParameterSpec params,
+ SecureRandom random
+ ) throws Exception {
+ // Create the XMLCipher element
+ XMLCipher cipher = XMLCipher.getInstance(encryptionMethod, null, null);
+
+ cipher.init(XMLCipher.WRAP_MODE, cert.getPublicKey());
+
+ EncryptedKey encryptedKey = cipher.encryptKey(doc, sessionKey, params, random);
+
+ KeyInfo builderKeyInfo = encryptedKey.getKeyInfo();
+ if (builderKeyInfo == null) {
+ builderKeyInfo = new KeyInfoEnc(doc);
+ encryptedKey.setKeyInfo(builderKeyInfo);
+ }
+
+ X509Data x509Data = new X509Data(doc);
+ x509Data.addCertificate(cert);
+ if (builderKeyInfo instanceof KeyInfoEnc
+ && ((KeyInfoEnc) builderKeyInfo).lengthAgreementMethod() > 0) {
+ AgreementMethod agreementMethod = ((KeyInfoEnc) builderKeyInfo).itemAgreementMethod(0);
+ agreementMethod.getRecipientKeyInfo().add(x509Data);
+ } else {
+ builderKeyInfo.add(x509Data);
+ }
+ return encryptedKey;
+ }
+
+ /**
+ * Generate a session key using the given algorithm
+ */
+ protected Key getSessionKey(String encryptionMethod) throws Exception {
+ // Generate a session key
+ KeyGenerator keyGen = KeyGenerator.getInstance("AES");
+ if (encryptionMethod.contains("128")) {
+ keyGen.init(128);
+ } else if (encryptionMethod.contains("192")) {
+ keyGen.init(192);
+ } else if (encryptionMethod.contains("256")) {
+ keyGen.init(256);
+ }
+ return keyGen.generateKey();
+ }
+
+ /**
+ * Encrypt a Document using the given parameters.
+ */
+ protected Document encryptDocument(
+ Document doc,
+ EncryptedKey encryptedKey,
+ Key sessionKey,
+ String encryptionMethod
+ ) throws Exception {
+ // Create the XMLCipher element
+ XMLCipher cipher = XMLCipher.getInstance(encryptionMethod);
+
+ cipher.init(XMLCipher.ENCRYPT_MODE, sessionKey);
+ EncryptedData builder = cipher.getEncryptedData();
+
+ KeyInfo builderKeyInfo = builder.getKeyInfo();
+ if (builderKeyInfo == null) {
+ builderKeyInfo = new KeyInfo(doc);
+ builder.setKeyInfo(builderKeyInfo);
+ }
+
+ builderKeyInfo.add(encryptedKey);
+
+ return cipher.doFinal(doc, doc.getDocumentElement());
+ }
+
+ /**
+ * Encrypt a Document using the given parameters.
+ */
+ protected Document encryptData(
+ Document doc,
+ EncryptedKey encryptedKey,
+ Key sessionKey,
+ String encryptionMethod,
+ InputStream dataToEncrypt
+ ) throws Exception {
+ // Create the XMLCipher element
+ XMLCipher cipher = XMLCipher.getInstance(encryptionMethod);
+
+ cipher.init(XMLCipher.ENCRYPT_MODE, sessionKey);
+ EncryptedData builder = cipher.getEncryptedData();
+
+ KeyInfo builderKeyInfo = builder.getKeyInfo();
+ if (builderKeyInfo == null) {
+ builderKeyInfo = new KeyInfo(doc);
+ builder.setKeyInfo(builderKeyInfo);
+ }
+
+ builderKeyInfo.add(encryptedKey);
+
+ EncryptedData endData = cipher.encryptData(doc, null, dataToEncrypt);
+ Element encDataElement = cipher.martial(endData);
+ doc.appendChild(encDataElement);
+ return doc;
+ }
+
+ /*
+ * Check we have retrieved a Credit Card number and that it is OK
+ * Check that the document has the correct number of nodes
+ */
+ protected void checkDecryptedDoc(Document d, boolean doNodeCheck) throws Exception {
+
+ String cc = XMLEncryption11TestAbstract.retrieveCCNumber(d);
+ LOG.log(System.Logger.Level.DEBUG, "Retrieved Credit Card : " + cc);
+ assertEquals(cardNumber, cc);
+
+ // Test cc numbers
+ if (doNodeCheck) {
+ int myNodeCount = XMLEncryption11TestAbstract.countNodes(d);
+
+ assertTrue(
+ myNodeCount > 0 && myNodeCount == nodeCount, "Node count mismatches"
+ );
+ }
+ }
+
+ protected String toString(Node n) throws Exception {
+ try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+ Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
+
+ c14n.canonicalizeSubtree(n, baos);
+ baos.flush();
+
+ return baos.toString(StandardCharsets.UTF_8);
+ }
+ }
+}
diff --git a/src/test/java/org/apache/xml/security/test/javax/xml/crypto/dsig/XMLSignatureBrainpoolTest.java b/src/test/java/org/apache/xml/security/test/javax/xml/crypto/dsig/XMLSignatureBrainpoolTest.java
new file mode 100644
index 00000000..3bf646a1
--- /dev/null
+++ b/src/test/java/org/apache/xml/security/test/javax/xml/crypto/dsig/XMLSignatureBrainpoolTest.java
@@ -0,0 +1,97 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.xml.security.test.javax.xml.crypto.dsig;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.Security;
+import java.security.cert.CertificateException;
+
+import org.apache.xml.security.testutils.JDKTestUtils;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+/**
+ * Unit test for brainpool javax.xml.crypto.dsig.XMLSignature creation. The tests
+ * require BouncyCastle provider to be activated. Please note also the setting of
+ * the DOMSignContext property "org.jcp.xml.dsig.internal.dom.SignatureProvider" to
+ * provide signature provider for the XMLSignature creation. SunJCE provider does
+ * not support brainpool curves signatures from JDK 15+
+ * <p />
+ * To execute just this tests class run the following command:
+ * <code>mvn test -Dtest=XMLSignatureBrainpoolTest -P bouncycastle</code>
+ * or to test it during the build start the project with the profile "bouncycastle"
+ * <code>mvn clean install -P bouncycastle</code>
+ */
+class XMLSignatureBrainpoolTest extends XMLSignatureAbstract {
+ protected static final System.Logger LOG = System.getLogger(XMLSignatureBrainpoolTest.class.getName());
+
+ private static final String ECDSA_KS_PATH =
+ "src/test/resources/org/apache/xml/security/samples/input/ecbrainpool.p12";
+ private static final String ECDSA_KS_PASSWORD = "security";
+ public static final String ECDSA_KS_TYPE = "PKCS12";
+
+
+ @BeforeAll
+ static void initProvider() {
+ Assumptions.assumeTrue(JDKTestUtils.getAuxiliaryProvider() != null, "BouncyCastle is required for this test");
+ Assumptions.assumeFalse("IBM Corporation".equals(System.getProperty("java.vendor")), "Skip for IBM JDK" );
+
+ Security.insertProviderAt(new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI(), 1);
+ }
+
+ @AfterAll
+ static void removeProvider() {
+ Security.removeProvider(org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI.class.getName());
+ }
+
+ @Override
+ KeyStore getKeyStore() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
+ KeyStore keyStore = KeyStore.getInstance(ECDSA_KS_TYPE);
+ keyStore.load(Files.newInputStream(Paths.get(ECDSA_KS_PATH)), ECDSA_KS_PASSWORD.toCharArray());
+ return keyStore;
+ }
+
+ @Override
+ char[] getKeyPassword() {
+ return ECDSA_KS_PASSWORD.toCharArray();
+ }
+
+ @ParameterizedTest
+ @CsvSource({"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256, brainpoolP256r1",
+ "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256, brainpoolP384r1",
+ "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256, brainpoolP512r1"
+ })
+ void createEdDSASignatureTest(String signatureAlgorithm, String alias) throws Exception {
+ byte[] buff = doSignWithJcpApi(signatureAlgorithm, alias, true);
+ if (LOG.isLoggable(System.Logger.Level.DEBUG)) {
+ Files.write(Paths.get("target","test-sign-"+alias+".xml"), buff);
+ }
+ Assertions.assertNotNull(buff);
+ assertValidSignatureWithJcpApi(buff, true);
+ }
+}
diff --git a/src/test/resources/org/apache/xml/security/samples/input/README.txt b/src/test/resources/org/apache/xml/security/samples/input/README.txt
new file mode 100644
index 00000000..10bd4fc1
--- /dev/null
+++ b/src/test/resources/org/apache/xml/security/samples/input/README.txt
@@ -0,0 +1,59 @@
+The file describes how keys for the test are generated. If you are adding new certificates
+please document creation procedure or source here.
+
+====
+ecbrainpool.p12
+
+Install latest OpenSSL 3.2.0 [23 Nov 2023], or just check the support brainpool EC.
+(https://www.openssl.org/news/openssl-3.2-notes.html)
+
+openssl ecparam -list_curves
+
+To generate the certificate for the brainpool curves, use the following script:
+create-brainpool-keystore.sh
+-----
+#!/bin/bash
+
+ALL_CERTS="brainpoolP256r1 brainpoolP384r1 brainpoolP512r1"
+KS_FILENAME="brainpool.p12"
+PASSPHRASE="security"
+
+
+for cert in ${ALL_CERTS}; \
+do \
+ echo "Generating certificate for ${cert}"; \
+ openssl ecparam -name ${cert} -genkey -noout -out ${cert}.pem
+ openssl ec -in ${cert}.pem -pubout -out ${cert}.pub
+ openssl req -x509 -nodes -sha256 -days 3650 \
+ -subj "/CN=${cert}/OU=eDeliveryAS4-2.0/OU=santuario/O=apache/C=EU" \
+ -addext "keyUsage=digitalSignature,keyEncipherment,dataEncipherment,cRLSign,keyCertSign" \
+ -addext "extendedKeyUsage=serverAuth,clientAuth" \
+ -key ${cert}.pem -out ${cert}.crt
+
+ echo "importing ${cert} to keystore";
+ openssl pkcs12 -export -out ${cert}.pfx -name ${cert} \
+ -inkey ${cert}.pem -in ${cert}.crt -passout pass:${PASSPHRASE}
+
+
+ echo "Merge ${cert} to common keystore";
+ /opt/java/jdk-17.0.9/bin/keytool -importkeystore -destkeystore ${KS_FILENAME} -deststoretype PKCS12 \
+ -destkeypass ${PASSPHRASE} -deststorepass ${PASSPHRASE} \
+ -srckeystore ${cert}.pfx -srcstoretype PKCS12 \
+ -srcstorepass ${PASSPHRASE} -srckeypass ${PASSPHRASE} \
+ -destalias ${cert} -srcalias ${cert}
+
+ echo "clean temp files for the ${cert}";
+ rm -f ${cert}.pem ${cert}.pub ${cert}.crt ${cert}.pfx;
+done
+-----
+
+====
+ecdsa.jks
+
+keytool -genkeypair -keystore ecdsa.jks -alias secp256r1 -keyalg EC -groupname secp256r1 \
+ -storepass security -keypass security \
+ -dname "CN=secp256r1,OU=ecdsa, OU=xmlsec,O=apache,C=EU" \
+ -validity 3650
+=====
+
+
diff --git a/src/test/resources/org/apache/xml/security/samples/input/ecbrainpool.p12 b/src/test/resources/org/apache/xml/security/samples/input/ecbrainpool.p12
new file mode 100644
index 00000000..1581feac
Binary files /dev/null and b/src/test/resources/org/apache/xml/security/samples/input/ecbrainpool.p12 differ