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/27 11:05:36 UTC
(santuario-xml-security-java) branch 3.0.x-fixes updated: Implementation of the HKDF derivation function (#271)
This is an automated email from the ASF dual-hosted git repository.
coheigea pushed a commit to branch 3.0.x-fixes
in repository https://gitbox.apache.org/repos/asf/santuario-xml-security-java.git
The following commit(s) were added to refs/heads/3.0.x-fixes by this push:
new 883ff16b Implementation of the HKDF derivation function (#271)
883ff16b is described below
commit 883ff16b4c93829ac05fee8ac769f98bbf4df882
Author: jrihtarsic <jr...@gmail.com>
AuthorDate: Mon May 27 12:16:28 2024 +0200
Implementation of the HKDF derivation function (#271)
* HKDF derivation function
* HKDF derivation function updates
* PR updates (docs and clean empty lines)
* Revert cleaning the code: empty lines from commit 491a7d36b69837b8db2b8192be5af117984ebb68
* PR: Update comments
* Fix PR comments
* Fix PR comments
* change XMLSecurityException with XMLEncryptionException for XMLCipherUtils.constructKeyDerivationParameter
* fx the type in the documentation
* Update branch with changes on main 'main' to fix build after merge
* Rename the confusing overloading of methods KeyUtils.deriveKeyEncryptionKey
* Remove XMLChipper.getJCEMacHashForUri URI/JCE name mapping and reuse JCEMapper.translateURItoJCEID
---------
Co-authored-by: RIHTARSIC Joze <jo...@ext.ec.europa.eu>
---
pom.xml | 6 +-
.../xml/security/encryption/AgreementMethod.java | 1 -
.../security/encryption/KeyDerivationMethod.java | 25 ++-
.../xml/security/encryption/XMLCipherUtil.java | 125 +++++++------
.../keys/content/AgreementMethodImpl.java | 111 ++++++++----
.../keys/content/derivedKey/ConcatKDF.java | 132 ++++----------
.../content/derivedKey/ConcatKDFParamsImpl.java | 2 +-
.../content/derivedKey/DerivationAlgorithm.java | 34 +---
.../encryption/keys/content/derivedKey/HKDF.java | 178 +++++++++++++++++++
.../keys/content/derivedKey/HKDFParamsImpl.java | 197 +++++++++++++++++++++
.../content/derivedKey/KDFParams.java} | 21 +--
.../derivedKey/KeyDerivationMethodImpl.java | 74 +++++---
.../encryption/params/ConcatKDFParams.java | 80 ++++++++-
.../xml/security/encryption/params/HKDFParams.java | 166 +++++++++++++++++
.../encryption/params/KeyDerivationParameters.java | 17 +-
.../security/resource/xmlsecurity_de.properties | 5 +-
.../security/resource/xmlsecurity_en.properties | 5 +-
.../xml/security/stax/ext/XMLSecurityUtils.java | 19 +-
.../input/AbstractSignatureInputHandler.java | 8 +-
.../org/apache/xml/security/utils/Constants.java | 6 +
.../apache/xml/security/utils/DERDecoderUtils.java | 5 +-
.../apache/xml/security/utils/ElementProxy.java | 3 +
.../xml/security/utils/EncryptionConstants.java | 23 ++-
.../org/apache/xml/security/utils/KeyUtils.java | 92 +++++++---
src/main/resources/bindings/dsig-more.xjb | 20 +++
src/main/resources/bindings/rsa-pss.xjb | 10 --
.../bindings/schemas/dsig-more_2001_04.xsd | 12 ++
.../bindings/schemas/dsig-more_2007_05.xsd | 39 ++++
.../bindings/schemas/dsig-more_2021_04.xsd | 35 ++++
src/main/resources/bindings/schemas/rsa-pss.xsd | 52 ------
.../keys/content/derivedKey/HKDFTest.java | 173 ++++++++++++++++++
.../dom/encryption/XMLCipherBrainpoolTest.java | 5 +-
.../test/dom/encryption/XMLCipherTest.java | 134 +++++++++++++-
.../encryption/XMLEncryption11BrainpoolTest.java | 4 +-
.../test/dom/encryption/XMLEncryption11Test.java | 9 +-
.../xml/security/testutils/KeyTestUtils.java | 1 +
36 files changed, 1447 insertions(+), 382 deletions(-)
diff --git a/pom.xml b/pom.xml
index 4bf83b1d..d43b2c89 100644
--- a/pom.xml
+++ b/pom.xml
@@ -345,20 +345,22 @@
<schemaInclude>bindings/schemas/exc-c14n.xsd</schemaInclude>
<schemaInclude>bindings/schemas/xmldsig-core-schema.xsd</schemaInclude>
<schemaInclude>bindings/schemas/xmldsig11-schema.xsd</schemaInclude>
+ <schemaInclude>bindings/schemas/dsig-more_2001_04.xsd</schemaInclude>
+ <schemaInclude>bindings/schemas/dsig-more_2007_05.xsd</schemaInclude>
+ <schemaInclude>bindings/schemas/dsig-more_2021_04.xsd</schemaInclude>
<schemaInclude>bindings/schemas/xenc-schema.xsd</schemaInclude>
<schemaInclude>bindings/schemas/xenc-schema-11.xsd</schemaInclude>
- <schemaInclude>bindings/schemas/rsa-pss.xsd</schemaInclude>
</schemaIncludes>
<bindingDirectory>${basedir}/src/main/resources/bindings/</bindingDirectory>
<bindingIncludes>
<bindingInclude>c14n.xjb</bindingInclude>
<bindingInclude>dsig.xjb</bindingInclude>
<bindingInclude>dsig11.xjb</bindingInclude>
+ <bindingInclude>dsig-more.xjb</bindingInclude>
<bindingInclude>xenc.xjb</bindingInclude>
<bindingInclude>xenc11.xjb</bindingInclude>
<bindingInclude>security-config.xjb</bindingInclude>
<bindingInclude>xop.xjb</bindingInclude>
- <bindingInclude>rsa-pss.xjb</bindingInclude>
</bindingIncludes>
<catalog>${basedir}/src/main/resources/bindings/bindings.cat</catalog>
<forceRegenerate>false</forceRegenerate>
diff --git a/src/main/java/org/apache/xml/security/encryption/AgreementMethod.java b/src/main/java/org/apache/xml/security/encryption/AgreementMethod.java
index 0339b3a2..03a4c005 100644
--- a/src/main/java/org/apache/xml/security/encryption/AgreementMethod.java
+++ b/src/main/java/org/apache/xml/security/encryption/AgreementMethod.java
@@ -91,7 +91,6 @@ public interface AgreementMethod {
*/
void setKANonce(byte[] kanonce);
-
/**
* Returns KeyDerivationMethod information used in the <code>AgreementMethod</code>.
* @return The KeyDerivationMethod information regarding the <code>AgreementMethod</code>.
diff --git a/src/main/java/org/apache/xml/security/encryption/KeyDerivationMethod.java b/src/main/java/org/apache/xml/security/encryption/KeyDerivationMethod.java
index b180043c..f2b168d8 100644
--- a/src/main/java/org/apache/xml/security/encryption/KeyDerivationMethod.java
+++ b/src/main/java/org/apache/xml/security/encryption/KeyDerivationMethod.java
@@ -19,10 +19,15 @@
package org.apache.xml.security.encryption;
+import org.apache.xml.security.encryption.keys.content.derivedKey.KDFParams;
+import org.apache.xml.security.exceptions.XMLSecurityException;
+
/**
- * The key derivation is to generate new cryptographic key material from existing key material such as the shared
- * secret and any other (private or public) information. The purpose of the key derivation is an extension of a given
- * but limited set of original key materials and to limit the use (exposure) of such key material.
+ * The key derivation is to generate new cryptographic key material from existing
+ * key material such as the shared secret and any other (private or public)
+ * information. The implementations of this interface provides XML serializing/deserializing
+ * of the: {@link org.apache.xml.security.encryption.params.KeyDerivationParameters} for
+ * various key derivation algorithms.
*
* The Schema for KeyDerivationMethod is as follows:
* <pre>
@@ -40,7 +45,19 @@ public interface KeyDerivationMethod {
/**
* Returns the algorithm URI of this <code>KeyDerivationMethod</code>.
*
- * @return the algorithm URI of this <code>KeyDerivationMethod</code>
+ * @return the algorithm URI string
*/
String getAlgorithm();
+
+ /**
+ * Returns the KDF parameters used by the key derivation algorithm.
+ * Currently supported types are:
+ * {@link org.apache.xml.security.encryption.params.ConcatKDFParams} and
+ * {@link org.apache.xml.security.encryption.params.HKDFParams}.
+ *
+ * @return the KDFParams used by the key derivation algorithm
+ * @throws XMLSecurityException if the KDFParams cannot be created
+ */
+ KDFParams getKDFParams() throws XMLSecurityException;
+
}
diff --git a/src/main/java/org/apache/xml/security/encryption/XMLCipherUtil.java b/src/main/java/org/apache/xml/security/encryption/XMLCipherUtil.java
index e84666c2..c48c2af7 100644
--- a/src/main/java/org/apache/xml/security/encryption/XMLCipherUtil.java
+++ b/src/main/java/org/apache/xml/security/encryption/XMLCipherUtil.java
@@ -24,6 +24,7 @@ import java.security.PrivilegedAction;
import java.security.PublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.MGF1ParameterSpec;
+import java.util.Base64;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
@@ -31,12 +32,14 @@ import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import org.apache.xml.security.algorithms.JCEMapper;
+import org.apache.xml.security.encryption.keys.content.derivedKey.ConcatKDFParamsImpl;
+import org.apache.xml.security.encryption.keys.content.derivedKey.HKDFParamsImpl;
+import org.apache.xml.security.encryption.keys.content.derivedKey.KDFParams;
import org.apache.xml.security.encryption.params.ConcatKDFParams;
+import org.apache.xml.security.encryption.params.HKDFParams;
import org.apache.xml.security.encryption.params.KeyAgreementParameters;
import org.apache.xml.security.encryption.params.KeyDerivationParameters;
import org.apache.xml.security.exceptions.XMLSecurityException;
-import org.apache.xml.security.encryption.keys.content.derivedKey.ConcatKDFParamsImpl;
-import org.apache.xml.security.encryption.keys.content.derivedKey.KeyDerivationMethodImpl;
import org.apache.xml.security.utils.EncryptionConstants;
import org.apache.xml.security.utils.KeyUtils;
@@ -46,17 +49,17 @@ public final class XMLCipherUtil {
org.slf4j.LoggerFactory.getLogger(XMLCipherUtil.class);
private static final boolean gcmUseIvParameterSpec =
- AccessController.doPrivileged((PrivilegedAction<Boolean>)
- () -> Boolean.getBoolean("org.apache.xml.security.cipher.gcm.useIvParameterSpec"));
+ AccessController.doPrivileged((PrivilegedAction<Boolean>)
+ () -> Boolean.getBoolean("org.apache.xml.security.cipher.gcm.useIvParameterSpec"));
/**
* Build an <code>AlgorithmParameterSpec</code> instance used to initialize a <code>Cipher</code> instance
* for block cipher encryption and decryption.
*
* @param algorithm the XML encryption algorithm URI
- * @param iv the initialization vector
+ * @param iv the initialization vector
* @return the newly constructed AlgorithmParameterSpec instance, appropriate for the
- * specified algorithm
+ * specified algorithm
*/
public static AlgorithmParameterSpec constructBlockCipherParameters(String algorithm, byte[] iv) {
if (EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM.equals(algorithm)
@@ -186,7 +189,6 @@ public final class XMLCipherUtil {
}
}
-
/**
* Construct an KeyAgreementParameterSpec object from the given parameters
*
@@ -215,7 +217,8 @@ public final class XMLCipherUtil {
/**
* Construct an KeyAgreementParameterSpec object from the given parameters
*
- * @param agreementAlgorithmURI agreement algorithm
+ * @param agreementAlgorithmURI agreement algorithm URI
+ * @param actorType the actor type (originator or recipient)
* @param keyDerivationParameter key derivation parameters (e.g. ConcatKDFParams for ConcatKDF key derivation)
* @param keyAgreementPrivateKey private key to derive the shared secret in case of Diffie-Hellman key agreements
* @param keyAgreementPublicKey public key to derive the shared secret in case of Diffie-Hellman key agreements
@@ -228,7 +231,7 @@ public final class XMLCipherUtil {
KeyAgreementParameters ecdhKeyAgreementParameters = new KeyAgreementParameters(
actorType,
agreementAlgorithmURI, keyDerivationParameter);
- if (actorType == KeyAgreementParameters.ActorType.RECIPIENT ) {
+ if (actorType == KeyAgreementParameters.ActorType.RECIPIENT) {
ecdhKeyAgreementParameters.setRecipientPrivateKey(keyAgreementPrivateKey);
ecdhKeyAgreementParameters.setOriginatorPublicKey(keyAgreementPublicKey);
} else {
@@ -240,65 +243,69 @@ public final class XMLCipherUtil {
}
/**
- * Construct a KeyDerivationParameter object from the given keyDerivationMethod and keyBitLength
+ * Construct a KeyDerivationParameter object from the given keyDerivationMethod data
+ * and keyBitLength.
*
- * @param keyDerivationMethod element to parse
- * @param keyBitLength expected derived key length
- * @return KeyDerivationParameter object
- * @throws XMLSecurityException if the keyDerivationMethod is not supported
+ * @param keyDerivationMethod element with the key derivation method data
+ * @param keyBitLength expected derived key length in bits
+ * @return KeyDerivationParameters data
+ * @throws XMLEncryptionException if KDFParams cannot be created or the
+ * KDF URI is not supported or the key derivation parameters are invalid
*/
- public static KeyDerivationParameters constructKeyDerivationParameter(KeyDerivationMethod keyDerivationMethod, int keyBitLength) throws XMLSecurityException {
+ public static KeyDerivationParameters constructKeyDerivationParameter(KeyDerivationMethod keyDerivationMethod,
+ int keyBitLength) throws XMLEncryptionException {
String keyDerivationAlgorithm = keyDerivationMethod.getAlgorithm();
- if (!EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF.equals(keyDerivationAlgorithm)) {
- throw new XMLEncryptionException("unknownAlgorithm", keyDerivationAlgorithm);
+ KDFParams kdfParams;
+ try {
+ kdfParams = keyDerivationMethod.getKDFParams();
+ } catch (XMLSecurityException e) {
+ throw new XMLEncryptionException(e);
}
- ConcatKDFParamsImpl concatKDFParams = ((KeyDerivationMethodImpl) keyDerivationMethod).getConcatKDFParams();
-
- return constructConcatKeyDerivationParameter(keyBitLength, concatKDFParams.getDigestMethod(), concatKDFParams.getAlgorithmId(),
- concatKDFParams.getPartyUInfo(), concatKDFParams.getPartyVInfo(),
- concatKDFParams.getSuppPubInfo(),concatKDFParams.getSuppPrivInfo());
-
- }
-
+ if (EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF.equals(keyDerivationAlgorithm)) {
+ if (!(kdfParams instanceof ConcatKDFParamsImpl)) {
+ throw new XMLEncryptionException("KeyDerivation.InvalidParametersType", keyDerivationAlgorithm, ConcatKDFParamsImpl.class.getName());
+ }
+ ConcatKDFParamsImpl concatKDFParams = (ConcatKDFParamsImpl) kdfParams;
+ return ConcatKDFParams.createBuilder(keyBitLength, concatKDFParams.getDigestMethod())
+ .algorithmID(concatKDFParams.getAlgorithmId())
+ .partyUInfo(concatKDFParams.getPartyUInfo())
+ .partyVInfo(concatKDFParams.getPartyVInfo())
+ .suppPubInfo(concatKDFParams.getSuppPubInfo())
+ .suppPrivInfo(concatKDFParams.getSuppPrivInfo())
+ .build();
- /**
- * Construct a ConcatKeyDerivationParameter object from the key length and digest method.
- *
- * @param keyBitLength expected derived key length
- * @param digestMethod digest method
- * @return ConcatKeyDerivationParameter object
- */
- public static ConcatKDFParams constructConcatKeyDerivationParameter(int keyBitLength,
- String digestMethod){
- return constructConcatKeyDerivationParameter(keyBitLength, digestMethod, null, null, null, null, null);
+ } else if (EncryptionConstants.ALGO_ID_KEYDERIVATION_HKDF.equals(keyDerivationAlgorithm)) {
+ if (!(kdfParams instanceof HKDFParamsImpl)) {
+ throw new XMLEncryptionException("KeyDerivation.InvalidParametersType", keyDerivationAlgorithm, HKDFParamsImpl.class.getName());
+ }
+ HKDFParamsImpl hKDFParams = (HKDFParamsImpl) kdfParams;
+ return HKDFParams.createBuilder(keyBitLength, hKDFParams.getPRFAlgorithm())
+ .salt(hKDFParams.getSalt() != null ? Base64.getDecoder().decode(hKDFParams.getSalt()) : null)
+ .info(hKDFParams.getInfo() != null ? Base64.getDecoder().decode(hKDFParams.getInfo()) : null)
+ .build();
+ }
+ throw new XMLEncryptionException("unknownAlgorithm", keyDerivationAlgorithm);
}
/**
- * Construct a ConcatKeyDerivationParameter object from the given parameters
+ * Method hexStringToByteArray converts hex string to byte array.
*
- * @param keyBitLength expected derived key length
- * @param digestMethod digest method
- * @param algorithmId algorithm id
- * @param partyUInfo partyUInfo
- * @param partyVInfo partyVInfo
- * @param suppPubInfo suppPubInfo
- * @param suppPrivInfo suppPrivInfo
- * @return ConcatKeyDerivationParameter object
+ * @param hexString the hex string to convert
+ * @return the byte array of the input param, empty array if the hex string is empty, or null if input param is null
*/
- public static ConcatKDFParams constructConcatKeyDerivationParameter(int keyBitLength,
- String digestMethod,
- String algorithmId,
- String partyUInfo,
- String partyVInfo,
- String suppPubInfo,
- String suppPrivInfo) {
-
- ConcatKDFParams kdp = new ConcatKDFParams(keyBitLength, digestMethod);
- kdp.setAlgorithmID(algorithmId);
- kdp.setPartyUInfo(partyUInfo);
- kdp.setPartyVInfo(partyVInfo);
- kdp.setSuppPubInfo(suppPubInfo);
- kdp.setSuppPrivInfo(suppPrivInfo);
- return kdp;
+ public static byte[] hexStringToByteArray(String hexString) {
+ if (hexString == null){
+ return null;
+ }
+ if (hexString.isEmpty()) {
+ return new byte[0];
+ }
+ int len = hexString.length();
+ byte[] data = new byte[len / 2];
+ for (int i = 0; i < len; i += 2) {
+ data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ + Character.digit(hexString.charAt(i+1), 16));
+ }
+ return data;
}
}
diff --git a/src/main/java/org/apache/xml/security/encryption/keys/content/AgreementMethodImpl.java b/src/main/java/org/apache/xml/security/encryption/keys/content/AgreementMethodImpl.java
index c7d62d76..1cf96e33 100644
--- a/src/main/java/org/apache/xml/security/encryption/keys/content/AgreementMethodImpl.java
+++ b/src/main/java/org/apache/xml/security/encryption/keys/content/AgreementMethodImpl.java
@@ -21,15 +21,18 @@ package org.apache.xml.security.encryption.keys.content;
import org.apache.xml.security.encryption.AgreementMethod;
import org.apache.xml.security.encryption.KeyDerivationMethod;
import org.apache.xml.security.encryption.XMLEncryptionException;
+import org.apache.xml.security.encryption.keys.OriginatorKeyInfo;
+import org.apache.xml.security.encryption.keys.RecipientKeyInfo;
+import org.apache.xml.security.encryption.keys.content.derivedKey.ConcatKDFParamsImpl;
+import org.apache.xml.security.encryption.keys.content.derivedKey.HKDFParamsImpl;
+import org.apache.xml.security.encryption.keys.content.derivedKey.KDFParams;
+import org.apache.xml.security.encryption.keys.content.derivedKey.KeyDerivationMethodImpl;
import org.apache.xml.security.encryption.params.ConcatKDFParams;
+import org.apache.xml.security.encryption.params.HKDFParams;
import org.apache.xml.security.encryption.params.KeyAgreementParameters;
import org.apache.xml.security.encryption.params.KeyDerivationParameters;
import org.apache.xml.security.exceptions.XMLSecurityException;
-import org.apache.xml.security.encryption.keys.OriginatorKeyInfo;
-import org.apache.xml.security.encryption.keys.RecipientKeyInfo;
import org.apache.xml.security.keys.content.KeyInfoContent;
-import org.apache.xml.security.encryption.keys.content.derivedKey.ConcatKDFParamsImpl;
-import org.apache.xml.security.encryption.keys.content.derivedKey.KeyDerivationMethodImpl;
import org.apache.xml.security.utils.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -37,15 +40,15 @@ import org.w3c.dom.Element;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PublicKey;
+import java.util.Base64;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
- * The implementation of the AgreementMethod interface. The element contains a information about
+ * The implementation of the AgreementMethod interface. The element contains information about
* the key agreement algorithm for deriving the encryption key.
- *
*/
public class AgreementMethodImpl extends EncryptionElementProxy implements KeyInfoContent, AgreementMethod {
private static final org.slf4j.Logger LOG =
@@ -59,12 +62,12 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
private String algorithmURI;
/**
- * Constructor AgreementMethodImpl for generating AgreementMethod from scratch based on {@link KeyAgreementParameters}.
- * The constructor generates {@link KeyDerivationMethod} if given and {@link OriginatorKeyInfo} based on originator
- * public key for ECDH-ES key agreement. It generates a placeholder element for RecipientKeyInfo. The recipient key info value
- * must be set later.
+ * Constructor AgreementMethodImpl for generating AgreementMethod from scratch based on {@link KeyAgreementParameters}.
+ * The constructor generates {@link KeyDerivationMethod} if given and {@link OriginatorKeyInfo} based on originator
+ * public key for ECDH-ES key agreement. It generates a placeholder element for RecipientKeyInfo. The recipient key info value
+ * must be set later.
*
- * @param doc the {@link Document} in which <code>AgreementMethod</code> will be placed
+ * @param doc the {@link Document} in which <code>AgreementMethod</code> will be placed
* @param keyAgreementParameter the {@link KeyAgreementParameters} from which <code>AgreementMethod</code> will be generated
* @throws XMLEncryptionException if the Key derivation algorithm is not supported or invalid parameters are given.
*/
@@ -76,7 +79,7 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
setKeyDerivationMethod(keyDerivationMethod);
}
// if ephemeral static key agreement then add originator public key automatically
- if (EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES.equals(keyAgreementParameter.getKeyAgreementAlgorithm())) {
+ if (keyAgreementParameter.getOriginatorPublicKey() != null) {
setOriginatorPublicKey(keyAgreementParameter.getOriginatorPublicKey());
}
// set recipient key info holder
@@ -163,6 +166,7 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
public KeyDerivationMethod getKeyDerivationMethod() throws XMLSecurityException {
if (keyDerivationMethod != null) {
+ LOG.debug("Returning cached KeyDerivationMethod");
return keyDerivationMethod;
}
@@ -170,11 +174,10 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
XMLUtils.selectXenc11Node(getElement().getFirstChild(), EncryptionConstants._TAG_KEYDERIVATIONMETHOD, 0);
if (keyDerivationMethodElement == null) {
+ LOG.debug("No KeyDerivationMethod element found!");
return null;
}
keyDerivationMethod = new KeyDerivationMethodImpl(keyDerivationMethodElement, baseURI);
-
-
return keyDerivationMethod;
}
@@ -199,6 +202,7 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
@Override
public OriginatorKeyInfo getOriginatorKeyInfo() throws XMLSecurityException {
if (originatorKeyInfo != null) {
+ LOG.debug("Returning cached OriginatorKeyInfo");
return originatorKeyInfo;
}
@@ -206,6 +210,7 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
XMLUtils.selectXencNode(getElement().getFirstChild(), EncryptionConstants._TAG_ORIGINATORKEYINFO, 0);
if (originatorKeyInfoElement == null) {
+ LOG.debug("No OriginatorKeyInfo element found!");
return null;
}
originatorKeyInfo = new OriginatorKeyInfo(originatorKeyInfoElement, baseURI);
@@ -228,7 +233,6 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
*/
@Override
public void setOriginatorPublicKey(PublicKey publicKey) {
-
OriginatorKeyInfo originatorKeyInfo = new OriginatorKeyInfo(getDocument());
originatorKeyInfo.add(publicKey);
setOriginatorKeyInfo(originatorKeyInfo);
@@ -240,6 +244,7 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
@Override
public RecipientKeyInfo getRecipientKeyInfo() throws XMLSecurityException {
if (recipientKeyInfo != null) {
+ LOG.debug("Returning cached RecipientKeyInfo");
return recipientKeyInfo;
}
@@ -247,6 +252,7 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
XMLUtils.selectXencNode(getElement().getFirstChild(), EncryptionConstants._TAG_RECIPIENTKEYINFO, 0);
if (recipientKeyInfoElement == null) {
+ LOG.debug("No RecipientKeyInfo element found!");
return null;
}
recipientKeyInfo = new RecipientKeyInfo(recipientKeyInfoElement, baseURI);
@@ -259,7 +265,6 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
*/
@Override
public void setRecipientKeyInfo(RecipientKeyInfo keyInfo) {
-
recipientKeyInfo = keyInfo;
appendSelf(keyInfo);
addReturnToSelf();
@@ -282,36 +287,54 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
}
/**
- * Method createKeyDerivationMethod creates a {@link KeyDerivationMethod} based on {@link KeyAgreementParameters}.
- * The method supports only {@link ConcatKDFParams} for now.
- * @see <a href="https://www.w3.org/TR/xmlenc-core1/#sec-ConcatKDF">ConcatKDF</a>
+ * Method creates a {@link KeyDerivationMethod} element based on parameters: {@link KeyAgreementParameters}.
+ * The method supports parameter types {@link ConcatKDFParams} and {@link HKDFParams}.
*
* @param keyAgreementParameter the {@link KeyAgreementParameters} from which {@link KeyDerivationMethod} will be generated.
- * @return the {@link KeyDerivationMethod} based on {@link KeyAgreementParameters}
- * @throws XMLEncryptionException if Key derivation algorithm is not supported
+ * @return the generated {@link KeyDerivationMethod} element based on {@link KeyAgreementParameters}
+ * @throws XMLEncryptionException if the Key derivation algorithm is not supported or invalid parameters are given.
+ * @throws IllegalArgumentException if KeyAgreementParameters is missing or wrong class type for derivation algorithm
*/
private KeyDerivationMethod createKeyDerivationMethod(KeyAgreementParameters keyAgreementParameter) throws XMLEncryptionException {
KeyDerivationParameters kdfParameters = keyAgreementParameter.getKeyDerivationParameter();
+ if (kdfParameters == null) {
+ throw new IllegalArgumentException("KeyAgreementParameters must have KeyDerivationParameters set!");
+ }
KeyDerivationMethodImpl keyDerivationMethod = new KeyDerivationMethodImpl(getDocument());
keyDerivationMethod.setAlgorithm(kdfParameters.getAlgorithm());
- if (kdfParameters instanceof ConcatKDFParams
- && EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF.equals(kdfParameters.getAlgorithm())) {
- ConcatKDFParamsImpl concatKDFParams = getConcatKDFParams((ConcatKDFParams)kdfParameters);
- keyDerivationMethod.setConcatKDFParams(concatKDFParams);
- } else {
- throw new XMLEncryptionException("Unsupported Key Derivation Algorithm");
+ KDFParams kdfParams;
+ switch (kdfParameters.getAlgorithm()) {
+ case EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF:
+ kdfParams = getConcatKDFParams(kdfParameters);
+ break;
+ case EncryptionConstants.ALGO_ID_KEYDERIVATION_HKDF:
+ kdfParams = getHKDFParams(kdfParameters);
+ break;
+ default:
+ throw new XMLEncryptionException("KeyDerivation.UnsupportedAlgorithm",
+ kdfParameters.getAlgorithm(), kdfParameters.getClass().getName());
}
+
+ keyDerivationMethod.setKDFParams(kdfParams);
return keyDerivationMethod;
}
/**
- * Method getConcatKDFParams creates a {@link ConcatKDFParamsImpl} based on {@link ConcatKDFParams}.
- * @param kdfParameters the {@link ConcatKDFParams} from which {@link ConcatKDFParamsImpl} will be generated.
+ * Method creates a {@link ConcatKDFParamsImpl} based on {@link ConcatKDFParams}.
+ *
+ * @param parameter the {@link KeyDerivationParameters} from which {@link ConcatKDFParamsImpl} will be generated.
* @return the {@link ConcatKDFParamsImpl}
+ * @throws IllegalArgumentException if parameter is not instance of {@link ConcatKDFParams}
*/
- private ConcatKDFParamsImpl getConcatKDFParams(ConcatKDFParams kdfParameters) {
+ private ConcatKDFParamsImpl getConcatKDFParams(KeyDerivationParameters parameter) {
+
+ if (!(parameter instanceof ConcatKDFParams)) {
+ throw new IllegalArgumentException("KDF Parameter must be instance of ConcatKDFParams");
+ }
+
+ ConcatKDFParams kdfParameters = (ConcatKDFParams) parameter;
ConcatKDFParamsImpl concatKDFParams = new ConcatKDFParamsImpl(getDocument());
concatKDFParams.setDigestMethod(kdfParameters.getDigestAlgorithm());
// set parameters
@@ -322,4 +345,32 @@ public class AgreementMethodImpl extends EncryptionElementProxy implements KeyIn
concatKDFParams.setSuppPrivInfo(kdfParameters.getSuppPrivInfo());
return concatKDFParams;
}
+
+ /**
+ * Method creates a {@link HKDFParamsImpl} based on {@link HKDFParams}.
+ *
+ * @param parameter the {@link KeyDerivationParameters} containing HKDF parameters.
+ * @return the {@link HKDFParamsImpl}
+ * @throws IllegalArgumentException if parameter is not instance of {@link HKDFParams}
+ */
+ private HKDFParamsImpl getHKDFParams(KeyDerivationParameters parameter) {
+
+ if (!(parameter instanceof HKDFParams)) {
+ throw new IllegalArgumentException("KDF Parameter must be instance of HKDFParams");
+ }
+ HKDFParams kdfParameters = (HKDFParams) parameter;
+
+ HKDFParamsImpl kdfParams = new HKDFParamsImpl(getDocument());
+ kdfParams.setPRFAlgorithm(kdfParameters.getHmacHashAlgorithm());
+ Base64.Encoder base64Encoder = Base64.getEncoder();
+ if (kdfParameters.getSalt() != null) {
+ kdfParams.setSalt(base64Encoder.encodeToString(kdfParameters.getSalt()));
+ }
+ if (kdfParameters.getInfo() != null) {
+ kdfParams.setInfo(base64Encoder.encodeToString(kdfParameters.getInfo()));
+ }
+ // set parameters
+ kdfParams.setKeyLength(kdfParameters.getKeyBitLength() / 8);
+ return kdfParams;
+ }
}
diff --git a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/ConcatKDF.java b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/ConcatKDF.java
index c6ee6518..3a65713a 100644
--- a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/ConcatKDF.java
+++ b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/ConcatKDF.java
@@ -6,9 +6,9 @@
* 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
- * <p>
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- * <p>
+ *
* 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
@@ -19,8 +19,11 @@
package org.apache.xml.security.encryption.keys.content.derivedKey;
import org.apache.xml.security.algorithms.MessageDigestAlgorithm;
+import org.apache.xml.security.encryption.XMLCipherUtil;
import org.apache.xml.security.encryption.XMLEncryptionException;
+import org.apache.xml.security.encryption.params.ConcatKDFParams;
import org.apache.xml.security.exceptions.XMLSecurityException;
+import org.apache.xml.security.utils.I18n;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -35,63 +38,42 @@ import java.util.List;
* <p>
* Identifier of the key derivation algorithm: http://www.w3.org/2009/xmlenc11#ConcatKDF
*/
-public class ConcatKDF implements DerivationAlgorithm {
+public class ConcatKDF implements DerivationAlgorithm<ConcatKDFParams> {
private static final org.slf4j.Logger LOG =
org.slf4j.LoggerFactory.getLogger(ConcatKDF.class.getName());
- private final String algorithmURI;
-
- /**
- * Constructor ConcatKDF with digest algorithmURI parameter such as http://www.w3.org/2001/04/xmlenc#sha256,
- * http://www.w3.org/2001/04/xmlenc#sha512, etc.
- */
- public ConcatKDF(String algorithmURI) {
- this.algorithmURI = algorithmURI;
- }
/**
- * Default Constructor which sets the default digest algorithmURI parameter: http://www.w3.org/2001/04/xmlenc#sha256,
- */
- public ConcatKDF() {
- this(MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256);
- }
-
- /**
- * Key DerivationAlgorithm implementation as defined in Section 5.8.1 of NIST SP 800-56A [SP800-56A]
- * <ul>
- * <li> reps = ⎡ keydatalen / hashlen⎤.</li>
- * <li> If reps > (2>32 −1), then ABORT: output an error indicator and stop.</li>
- * <li> Initialize a 32-bit, big-endian bit string counter as 0000000116.</li>
- * <li> If counter || Z || OtherInfo is more than max_hash_inputlen bits long, then ABORT: output an error indicator and stop.
- * <li> For i = 1 to reps by 1, do the following:<ul>
- * <li> Compute Hashi = H(counter || Z || OtherInfo).</li>
- * <li> Increment counter (modulo 232), treating it as an unsigned 32-bit integer.</li>
- * </ul></li>
- * <li> Let Hhash be set to Hashreps if (keydatalen / hashlen) is an integer; otherwise, let Hhash be set to the
- * (keydatalen mod hashlen) leftmost bits of Hashreps.</li>
- * <li>Set DerivedKeyingMaterial = Hash1 || Hash2 || ... || Hashreps-1 || Hhash</li>
- * </ul>
+ * Derives a key from the shared secret and other concat kdf parameters.
*
- * @param secret The "shared" secret to use for key derivation (e.g. the secret key)
- * @param otherInfo as specified in [SP800-56A] the optional attributes: AlgorithmID, PartyUInfo, PartyVInfo, SuppPubInfo and SuppPrivInfo attributes are concatenated to form a bit string “OtherInfo” that is used with the key derivation function.
- * @param offset the offset parameter is ignored by this implementation.
- * @param keyLength The length of the key to derive
- * @return The derived key
- * @throws XMLEncryptionException if the key length is too long to be derived with the given algorithm
+ * @param sharedSecret The "shared" secret used for the key derivation (e.g. the secret key)
+ * @param concatKDFParams The concat key derivation parameters
+ * @return the derived key bytes
+ * @throws IllegalArgumentException if the concat KDF parameters are not set
+ * @throws XMLSecurityException if the key derivation parameters are invalid
*/
@Override
- public byte[] deriveKey(byte[] secret, byte[] otherInfo, int offset, long keyLength) throws XMLSecurityException {
+ public byte[] deriveKey(byte[] sharedSecret, ConcatKDFParams concatKDFParams) throws XMLSecurityException {
+
+ // check if the parameters are set
+ if (concatKDFParams == null) {
+ throw new IllegalArgumentException(I18n.translate("KeyDerivation.MissingParameters"));
+ }
- MessageDigest digest = MessageDigestAlgorithm.getDigestInstance(algorithmURI);
+ // concatenate the bitstrings in following order algID || partyUInfo || partyVInfo || suppPubInfo || suppPrivInfo
+ final byte[] otherInfo = concatParameters(concatKDFParams.getAlgorithmID(),
+ concatKDFParams.getPartyUInfo(), concatKDFParams.getPartyVInfo(),
+ concatKDFParams.getSuppPubInfo(), concatKDFParams.getSuppPrivInfo());
- long genKeyLength = offset+keyLength;
+ // get the digest algorithm
+ MessageDigest digest = MessageDigestAlgorithm.getDigestInstance(concatKDFParams.getDigestAlgorithm());
+ int genKeyLength = concatKDFParams.getKeyLength();
int iDigestLength = digest.getDigestLength();
- if (genKeyLength / iDigestLength > (long) Integer.MAX_VALUE) {
- LOG.error("Key size is to long to be derived with hash algorithm [{0}]", algorithmURI);
- throw new XMLEncryptionException("errorInKeyDerivation");
+ if (genKeyLength / (long) iDigestLength > Integer.MAX_VALUE) {
+ throw new XMLSecurityException("KeyDerivation.InvalidParameter", new Object[]{"key length"} );
}
- int toGenerateSize = (int) genKeyLength;
+ int toGenerateSize = genKeyLength;
digest.reset();
ByteBuffer indexBuffer = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN);
@@ -104,57 +86,17 @@ public class ConcatKDF implements DerivationAlgorithm {
indexBuffer.putInt(counter++);
indexBuffer.position(0);
digest.update(indexBuffer);
- digest.update(secret);
+ digest.update(sharedSecret);
if (otherInfo != null && otherInfo.length > 0) {
digest.update(otherInfo);
}
result.put(digest.digest(), 0, Math.min(toGenerateSize, iDigestLength));
toGenerateSize -= iDigestLength;
}
- if (offset > 0) {
- result.position(offset);
- return result.slice().array();
- }
- return result.array();
- }
- /**
- * Method concatenate the bitstrings in following order {@code algID || partyUInfo || partyVInfo || suppPubInfo || suppPrivInfo}.
- * to crate otherInfo as key derivation function input.
- * If named parameters are null the value is ignored.
- * Method parses the bitstring firs {{@code @See} https://www.w3.org/TR/xmlenc-core1/#sec-ConcatKDF} and then concatenates them to a byte array.
- *
- * @param sharedSecret The "shared" secret to use for key derivation (e.g. the secret key)
- * @param algID A bit string that indicates how the derived keying material will be parsed and for which
- * algorithm(s) the derived secret keying material will be used.
- * @param partyUInfo A bit string containing public information that is required by the
- * application using this KDF to be contributed by party U to the key derivation
- * process. At a minimum, PartyUInfo shall include IDU, the identifier of party U. See
- * the notes below..
- * @param partyVInfo A bit string containing public information that is required by the
- * application using this KDF to be contributed by party V to the key derivation
- * process. At a minimum, PartyVInfo shall include IDV, the identifier of party V. See
- * the notes below.
- * @param suppPubInfo bit string containing additional, mutually-known public information.
- * @param suppPrivInfo The suppPrivInfo A bit string containing additional, mutually-known public Information.
- * @param keyLength The length of the key to derive
- * @return The resulting other info.
- */
- public byte[] deriveKey(final byte[] sharedSecret,
- final String algID,
- final String partyUInfo,
- final String partyVInfo,
- final String suppPubInfo,
- final String suppPrivInfo,
- final long keyLength)
- throws XMLSecurityException {
-
- final byte[] otherInfo = concatParameters(algID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
-
- return deriveKey(sharedSecret, otherInfo, keyLength);
+ return result.array();
}
-
/**
* Simple method to concatenate non-padded bitstream ConcatKDF parameters.
* If parameters are null the value is ignored.
@@ -217,22 +159,16 @@ public class ConcatKDF implements DerivationAlgorithm {
LOG.error("Padded ConcatKDF parameters are not supported");
throw new XMLEncryptionException( "KeyDerivation.NotSupportedParameter", kdfParameter);
}
- // skip first two chars
+ // skip first two chars since they are padding bytes,
kdfP = kdfP.substring(2);
- paramLen = kdfP.length();
- byte[] data = new byte[paramLen / 2];
-
- for (int i = 0; i < paramLen; i += 2) {
- data[i / 2] = (byte) ((Character.digit(kdfP.charAt(i), 16) << 4)
- + Character.digit(kdfP.charAt(i + 1), 16));
- }
- return data;
+ return XMLCipherUtil.hexStringToByteArray(kdfP);
}
/**
* Method returns the size of the array or 0 if the array is null.
+ *
* @param array the array to get the size from
- * @return the size of the array or 0 if the array is null.
+ * @return the size of the array or 0 if the array is null
*/
private static int getSize(byte[] array) {
return array == null ? 0 : array.length;
diff --git a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/ConcatKDFParamsImpl.java b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/ConcatKDFParamsImpl.java
index fcc7b4e1..323b2ce5 100644
--- a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/ConcatKDFParamsImpl.java
+++ b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/ConcatKDFParamsImpl.java
@@ -28,7 +28,7 @@ import java.util.StringJoiner;
/**
* Class ConcatKDFParamsImpl is an DOM representation of the ConcatKDFParams.
*/
-public class ConcatKDFParamsImpl extends Encryption11ElementProxy {
+public class ConcatKDFParamsImpl extends Encryption11ElementProxy implements KDFParams {
/**
diff --git a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/DerivationAlgorithm.java b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/DerivationAlgorithm.java
index 3f24b445..3b11ab19 100644
--- a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/DerivationAlgorithm.java
+++ b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/DerivationAlgorithm.java
@@ -18,38 +18,22 @@
*/
package org.apache.xml.security.encryption.keys.content.derivedKey;
+import org.apache.xml.security.encryption.params.KeyDerivationParameters;
import org.apache.xml.security.exceptions.XMLSecurityException;
/**
- * Interface is supported by classes to implement key derivation algorithms.
+ * The DerivationAlgorithm is the base interface for all key derivation algorithms
+ * implementation.
*/
-public interface DerivationAlgorithm {
-
- /**
- * Derives a key from the given secret and other info. The initial derived key is size of
- * offset + keyLength.
- *
- * @param secret The "shared" secret to use for key derivation (e.g. the secret key)
- * @param otherInfo as specified in [SP800-56A] the optional attributes: AlgorithmID, PartyUInfo, PartyVInfo, SuppPubInfo and SuppPrivInfo attributes are concatenated to form a bit string “OtherInfo” that is used with the key derivation function.
- * @param offset the starting position in derived keying material of size: offset + keyLength
- * @param keyLength The length of the key to derive
- * @return The derived key
- * @throws XMLSecurityException if something goes wrong during the key derivation
- */
- byte[] deriveKey(byte[] secret, byte[] otherInfo, int offset,
- long keyLength) throws XMLSecurityException;
-
+public interface DerivationAlgorithm<T extends KeyDerivationParameters> {
/**
* Derives a key from the given secret and other info.
+ *
* @param secret The "shared" secret to use for key derivation (e.g. the secret key)
- * @param otherInfo as specified in [SP800-56A] the optional attributes: AlgorithmID, PartyUInfo, PartyVInfo, SuppPubInfo and SuppPrivInfo attributes are concatenated to form a bit string “OtherInfo” that is used with the key derivation function.
- * @param keyLength The length of the key to derive
- * @return The derived key
- * @throws XMLSecurityException if something goes wrong during the key derivation
+ * @param params The key derivation parameters implementing the KeyDerivationParameters interface
+ * @return Byte array of the derived key
+ * @throws XMLSecurityException in case of derivation error or invalid parameters
*/
- default byte[] deriveKey(byte[] secret, byte[] otherInfo,
- long keyLength) throws XMLSecurityException {
- return deriveKey(secret, otherInfo, 0, keyLength);
- }
+ byte[] deriveKey(byte[] secret, T params) throws XMLSecurityException;
}
diff --git a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDF.java b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDF.java
new file mode 100644
index 00000000..a1b31eba
--- /dev/null
+++ b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDF.java
@@ -0,0 +1,178 @@
+/**
+ * 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.encryption.keys.content.derivedKey;
+
+import org.apache.xml.security.algorithms.JCEMapper;
+import org.apache.xml.security.encryption.params.HKDFParams;
+import org.apache.xml.security.exceptions.XMLSecurityException;
+import org.apache.xml.security.utils.I18n;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.ByteBuffer;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * The implementation of the HMAC-based Extract-and-Expand Key Derivation Function (HKDF)
+ * as defined in <a href="https://datatracker.ietf.org/doc/html/rfc5869">RFC 5869</a>.
+ * <p>
+ * The HKDF algorithm is defined as follows:
+ * <pre>
+ * N = ceil(L/HashLen)
+ * T = T(1) | T(2) | T(3) | ... | T(N)
+ * OKM = first L bytes of T
+ * where:
+ * T(0) = empty string (zero length)
+ * T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
+ * T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
+ * T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
+ * ...
+ * </pre>
+ */
+public class HKDF implements DerivationAlgorithm<HKDFParams> {
+
+ private static final org.slf4j.Logger LOG =
+ org.slf4j.LoggerFactory.getLogger(HKDF.class);
+
+ /**
+ * Derive a key using the HMAC-based Extract-and-Expand Key Derivation Function (HKDF)
+ * as defined in <a href="https://datatracker.ietf.org/doc/html/rfc5869">RFC 5869</a>.
+ *
+ * @param secret The "shared" secret to use for key derivation
+ * @param params The key derivation parameters (salt, info, key length, ...)
+ * @return The derived key of the specified length in bytes defined in the params
+ * @throws IllegalArgumentException if the parameters are missing
+ * @throws XMLSecurityException if the hmac hash algorithm is not supported
+ */
+ @Override
+ public byte[] deriveKey(byte[] secret, HKDFParams params) throws XMLSecurityException {
+ // check if the parameters are set
+ if (params == null) {
+ throw new IllegalArgumentException(I18n.translate("KeyDerivation.MissingParameters"));
+ }
+
+ String jceAlgorithmName = JCEMapper.translateURItoJCEID(params.getHmacHashAlgorithm());
+ if (jceAlgorithmName == null) {
+ throw new XMLSecurityException("KeyDerivation.NotSupportedParameter", new Object[]{params.getHmacHashAlgorithm()});
+ }
+
+ byte[] prk = extractKey(jceAlgorithmName, params.getSalt(), secret);
+ return expandKey(jceAlgorithmName, prk, params.getInfo(), params.getKeyLength());
+ }
+
+ /**
+ * The method "extracts" the pseudo-random key (PRK) based on HMAC-Hash function
+ * (optional) salt value (a non-secret random value) and the shared secret/input
+ * keying material (IKM).
+ * Calculation of the extracted key:
+ * <pre>PRK = HMAC-Hash(salt, IKM)</pre>
+ *
+ * @param jceAlgorithmName the java JCE HMAC algorithm name to use for key derivation
+ * (e.g. HmacSHA256, HmacSHA384, HmacSHA512)
+ * @param salt the optional salt value (a non-secret random value);
+ * @param secret the shared secret/input keying material (IKM) to use for
+ * key derivation
+ * @return the pseudo-random key bytes
+ * @throws XMLSecurityException if the jceAlgorithmName is not supported
+ */
+ public byte[] extractKey(String jceAlgorithmName, byte[] salt, byte[] secret) throws XMLSecurityException {
+ Mac hMac = initHMac(jceAlgorithmName, salt, true);
+ hMac.reset();
+ return hMac.doFinal(secret);
+ }
+
+ /**
+ * The method inits Hash-MAC with given PRK (as salt) and output OKM is calculated as follows:
+ * <pre>
+ * T(0) = empty string (zero length)
+ * T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
+ * T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
+ * T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
+ * ...
+ * </pre>
+ *
+ * @param jceHmacAlgorithmName the java JCE HMAC algorithm name to use to expand
+ * the key (e.g. HmacSHA256, HmacSHA384, HmacSHA512)
+ * @param prk pseudo-random key derived from the shared secret
+ * @param info used to derive the key
+ * @param keyLength key length in bytes of the derived key
+ * @return the output keying material (OKM) size of keyLength octets
+ * @throws XMLSecurityException if the jceHmacAlgorithmName is not supported
+ */
+ public byte[] expandKey(String jceHmacAlgorithmName, byte[] prk, byte[] info, long keyLength) throws XMLSecurityException {
+ // prepare for expanding the key
+ Mac hMac = initHMac(jceHmacAlgorithmName, prk, false);
+ int iMacLength = hMac.getMacLength();
+
+ int toGenerateSize = (int) keyLength;
+ ByteBuffer result = ByteBuffer.allocate(toGenerateSize);
+ byte[] prevResult = new byte[0];
+ short counter = 1;
+ while (toGenerateSize > 0) {
+ hMac.reset();
+ hMac.update(prevResult);
+ if (info != null && info.length > 0) {
+ hMac.update(info);
+ }
+ hMac.update((byte) counter);
+ prevResult = hMac.doFinal();
+ result.put(prevResult, 0, Math.min(toGenerateSize, iMacLength));
+ // get ready for next iteration
+ toGenerateSize -= iMacLength;
+ counter++;
+ }
+ return result.array();
+ }
+
+ /**
+ * Method initializes a Message Authentication Code (MAC) object using the
+ * init secret/salt or an empty byte array if initSecret parameter is null or empty.
+ *
+ * @param jceAlgorithmName the java JCE HMAC algorithm name to use to init Mac
+ * @param initSecret the secret/salt to initialize the hmac
+ * @param initPRK if true, the salt is initialized with a string of zero octets
+ * as long as the hash function output see [RFC5869] Section 2.2
+ * @return Initialized Mac object
+ * @throws XMLSecurityException if the hmac algorithm is not supported or if it
+ * fails to initialize
+ */
+ private Mac initHMac(String jceAlgorithmName, byte[] initSecret, boolean initPRK) throws XMLSecurityException {
+ Mac mac;
+ try {
+ LOG.debug("Init Mac with hash algorithm: [{}]", jceAlgorithmName);
+ mac = Mac.getInstance(jceAlgorithmName);
+ } catch (NoSuchAlgorithmException e) {
+ throw new XMLSecurityException(e, "KeyDerivation.NotSupportedParameter", new Object[]{jceAlgorithmName});
+ }
+
+ if (initPRK && (initSecret == null || initSecret.length == 0)) {
+ // If "initSecret"/salt is not provided, a string of zero octets as long as the hash function output is used
+ LOG.debug("Init Mac with hmac algorithm [{}] and empty salt!", jceAlgorithmName);
+ initSecret = new byte[mac.getMacLength()];
+ }
+ SecretKeySpec secretKey = new SecretKeySpec(initSecret, jceAlgorithmName);
+ try {
+ mac.init(secretKey);
+ } catch (InvalidKeyException e) {
+ throw new XMLSecurityException(e);
+ }
+ return mac;
+ }
+}
diff --git a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDFParamsImpl.java b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDFParamsImpl.java
new file mode 100644
index 00000000..5fcc28e1
--- /dev/null
+++ b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDFParamsImpl.java
@@ -0,0 +1,197 @@
+/**
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.encryption.keys.content.derivedKey;
+
+import org.apache.xml.security.exceptions.XMLSecurityException;
+import org.apache.xml.security.utils.Constants;
+import org.apache.xml.security.utils.ElementProxy;
+import org.apache.xml.security.utils.EncryptionConstants;
+import org.apache.xml.security.utils.XMLUtils;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Class HKDFParamsImpl is an DOM representation of the HKDF Parameters.
+ */
+public class HKDFParamsImpl extends ElementProxy implements KDFParams {
+
+ private static final org.slf4j.Logger LOG =
+ org.slf4j.LoggerFactory.getLogger(HKDFParamsImpl.class);
+
+ /**
+ * Constructor creates a new HKDFParamsImpl instance.
+ *
+ * @param doc the Document in which to create the DOM tree
+ */
+ public HKDFParamsImpl(Document doc) {
+ super(doc);
+ }
+
+ /**
+ * Constructor HKDFParamsImpl from existing XML element
+ *
+ * @param element the element to use as source
+ * @param baseURI the URI of the resource where the XML instance was stored
+ * @throws XMLSecurityException if the construction fails for any reason
+ */
+ public HKDFParamsImpl(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
+ }
+
+ /**
+ * Sets the <code>DigestMethod</code> Element
+ *
+ * @param hmacHashAlgorithm is the digest method URI value.
+ */
+ public void setPRFAlgorithm(String hmacHashAlgorithm) {
+ Element targetElement =
+ XMLUtils.selectNode(getElement().getFirstChild(), getBaseNamespace(), EncryptionConstants._TAG_PRF, 0);
+
+ if (hmacHashAlgorithm == null) {
+ LOG.debug("HMAC Hash Method is null!");
+ if (targetElement != null) {
+ LOG.debug("HMAC Hash Method is null, removing PRF element");
+ targetElement.getParentNode().removeChild(targetElement);
+ }
+ return;
+ }
+
+ if (targetElement == null) {
+ targetElement = createElementForFamilyLocal(getBaseNamespace(), EncryptionConstants._TAG_PRF);
+ appendSelf(targetElement);
+ }
+ targetElement.setAttributeNS(null, Constants._ATT_ALGORITHM, hmacHashAlgorithm);
+ }
+
+ /**
+ * Returns the <code>DigestMethod</code> algorithm value.
+ *
+ * @return the digest method URI value.
+ */
+ public String getPRFAlgorithm() {
+ Element prfElement =
+ XMLUtils.selectXenc11Node(getElement().getFirstChild(), EncryptionConstants._TAG_PRF, 0);
+ if (prfElement != null) {
+ return prfElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+ }
+ return null;
+ }
+
+ /**
+ * Sets the <code>Info</code> attribute
+ *
+ * @param info hex encoded string for the info attribute
+ */
+ public void setInfo(String info) {
+ setLocalElementValue(info, EncryptionConstants._TAG_INFO);
+ }
+
+ /**
+ * Returns the hex encoded <code>Info</code> attribute
+ *
+ * @return the info attribute value.
+ */
+ public String getInfo() {
+ return getLocalElementValue(EncryptionConstants._TAG_INFO);
+ }
+
+ /**
+ * Sets the <code>keyLength</code> attribute. If the keyLength value null, the attribute is ignored.
+ *
+ * @param keyLength length of the derived key in bytes.
+ */
+ public void setKeyLength(Integer keyLength) {
+ setLocalElementValue(keyLength != null ? keyLength.toString() : null, EncryptionConstants._TAG_KEYLENGTH);
+ }
+
+ /**
+ * Returns the <code>keyLength</code> attribute value.
+ *
+ * @return the keyLength attribute value.
+ */
+ public Integer getKeyLength() {
+ String keyLengthStr = getLocalElementValue(EncryptionConstants._TAG_KEYLENGTH);
+ Integer keyLength = null;
+ if (keyLengthStr != null) {
+ try {
+ keyLength = Integer.parseInt(keyLengthStr);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid key length: " + keyLengthStr);
+ }
+ }
+ return keyLength;
+ }
+
+ /**
+ * Sets the <code>Salt</code> Element
+ *
+ * @param salt is base64 encoded bytearray.
+ */
+ public void setSalt(String salt) {
+ setLocalElementValue(salt, Constants._TAG_SALT);
+ }
+
+ /**
+ * Returns the <code>Salt</code> Element value.
+ *
+ * @return the salt value is base64 encoded bytearray value.
+ */
+ public String getSalt() {
+ return getLocalElementValue(Constants._TAG_SALT);
+ }
+
+ @Override
+ public String getBaseLocalName() {
+ return EncryptionConstants._TAG_HKDFPARAMS;
+ }
+
+ @Override
+ public String getBaseNamespace() {
+ return Constants.XML_DSIG_NS_MORE_21_04;
+ }
+
+ public void setLocalElementValue(String value, String elementName) {
+ Element targetElement =
+ XMLUtils.selectNode(getElement().getFirstChild(), getBaseNamespace(), elementName, 0);
+
+ if (value == null) {
+ LOG.debug("Element value: [%s] is null!", elementName);
+ if (targetElement != null) {
+ LOG.debug("Element value: [%s] is null. Remove element!", elementName);
+ targetElement.getParentNode().removeChild(targetElement);
+ }
+ return;
+ }
+ if (targetElement == null) {
+ targetElement = createElementForFamilyLocal(getBaseNamespace(), elementName);
+ appendSelf(targetElement);
+ }
+ targetElement.setTextContent(value);
+ }
+
+ public String getLocalElementValue(String elementName) {
+ Element targetElement =
+ XMLUtils.selectNode(getElement().getFirstChild(), getBaseNamespace(), elementName, 0);
+
+ if (targetElement != null) {
+ return XMLUtils.getFullTextChildrenFromNode(targetElement);
+ }
+ return null;
+ }
+}
diff --git a/src/main/java/org/apache/xml/security/encryption/params/KeyDerivationParameters.java b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/KDFParams.java
similarity index 56%
copy from src/main/java/org/apache/xml/security/encryption/params/KeyDerivationParameters.java
copy to src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/KDFParams.java
index e22dbff8..0c28ba9c 100644
--- a/src/main/java/org/apache/xml/security/encryption/params/KeyDerivationParameters.java
+++ b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/KDFParams.java
@@ -16,26 +16,11 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.xml.security.encryption.params;
+package org.apache.xml.security.encryption.keys.content.derivedKey;
/**
- * Abstract key derivation class contains the basic parameters used for the key derivation.
- * The class should be extended to provide algorithm specific parameters.
+ * Marker interface for all KDFParams implementations.
*/
-public abstract class KeyDerivationParameters {
- private final String algorithm;
- private final int keyBitLength;
+public interface KDFParams {
- public KeyDerivationParameters(String algorithm, int keyLength) {
- this.algorithm = algorithm;
- this.keyBitLength = keyLength;
- }
-
- public String getAlgorithm() {
- return algorithm;
- }
-
- public int getKeyBitLength() {
- return keyBitLength;
- }
}
diff --git a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/KeyDerivationMethodImpl.java b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/KeyDerivationMethodImpl.java
index 8f59e8db..477aacf5 100644
--- a/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/KeyDerivationMethodImpl.java
+++ b/src/main/java/org/apache/xml/security/encryption/keys/content/derivedKey/KeyDerivationMethodImpl.java
@@ -20,20 +20,20 @@ package org.apache.xml.security.encryption.keys.content.derivedKey;
import org.apache.xml.security.encryption.KeyDerivationMethod;
import org.apache.xml.security.exceptions.XMLSecurityException;
-import org.apache.xml.security.utils.Encryption11ElementProxy;
-import org.apache.xml.security.utils.EncryptionConstants;
-import org.apache.xml.security.utils.XMLUtils;
+import org.apache.xml.security.utils.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.StringJoiner;
/**
- * Class KeyDerivationMethodImpl is an DOM implementation of the KeyDerivationMethod
- *
+ * Class KeyDerivationMethodImpl is an DOM implementation of the KeyDerivationMethod.
*/
public class KeyDerivationMethodImpl extends Encryption11ElementProxy implements KeyDerivationMethod {
- private ConcatKDFParamsImpl concatKDFParams;
+ private static final org.slf4j.Logger LOG =
+ org.slf4j.LoggerFactory.getLogger(KeyDerivationMethodImpl.class);
+
+ private KDFParams kdfParams;
/**
* Constructor KeyDerivationMethodImpl creates a new KeyDerivationMethodImpl instance.
@@ -45,7 +45,7 @@ public class KeyDerivationMethodImpl extends Encryption11ElementProxy implements
}
/**
- * Constructor KeyDerivationMethodImpl from existing XML element
+ * Constructor KeyDerivationMethodImpl from existing XML element.
*
* @param element the element to use as source
* @param baseURI the URI of the resource where the XML instance was stored
@@ -56,9 +56,9 @@ public class KeyDerivationMethodImpl extends Encryption11ElementProxy implements
}
/**
- * Sets the <code>Algorithm</code> attribute
+ * Sets the <code>Algorithm</code> attribute.
*
- * @param algorithm ID
+ * @param algorithm URI
*/
public void setAlgorithm(String algorithm) {
if (algorithm != null) {
@@ -71,29 +71,53 @@ public class KeyDerivationMethodImpl extends Encryption11ElementProxy implements
return getLocalAttribute(EncryptionConstants._ATT_ALGORITHM);
}
- public ConcatKDFParamsImpl getConcatKDFParams() throws XMLSecurityException {
-
- if (concatKDFParams != null) {
- return concatKDFParams;
- }
- Element concatKDFParamsElement =
- XMLUtils.selectXenc11Node(getElement().getFirstChild(), EncryptionConstants._TAG_CONCATKDFPARAMS, 0);
+ /**
+ * Method returns the KDFParams object of this KeyDerivationMethod Element.
+ * If the KDFParams object is not set/cached, it tries to parse it (and cache it)
+ * from the KeyDerivationMethod Element. If the KDFParams cannot be parsed/or the
+ * Key derivation function URI is not supported, an XMLSecurityException is thrown.
+ *
+ * @return the Key derivation function parameters.
+ * @throws XMLSecurityException if the KDFParams cannot be created or the KDF URI is not supported.
+ */
+ @Override
+ public KDFParams getKDFParams() throws XMLSecurityException {
- if (concatKDFParamsElement == null) {
- return null;
+ if (kdfParams != null) {
+ LOG.debug("Returning cached KDFParams");
+ return kdfParams;
}
- concatKDFParams = new ConcatKDFParamsImpl(concatKDFParamsElement, getBaseURI());
- return concatKDFParams;
+ String kdfAlgorithm = getAlgorithm();
+ if (EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF.equals(kdfAlgorithm)) {
+ Element concatKDFParamsElement =
+ XMLUtils.selectXenc11Node(getElement().getFirstChild(),
+ EncryptionConstants._TAG_CONCATKDFPARAMS, 0);
+ kdfParams = new ConcatKDFParamsImpl(concatKDFParamsElement, getBaseURI());
+ } else if (EncryptionConstants.ALGO_ID_KEYDERIVATION_HKDF.equals(kdfAlgorithm)) {
+ Element hkdfParamsElement =
+ XMLUtils.selectNode(getElement().getFirstChild(),
+ Constants.XML_DSIG_NS_MORE_21_04,
+ EncryptionConstants._TAG_HKDFPARAMS, 0);
+ kdfParams = new HKDFParamsImpl(hkdfParamsElement, Constants.XML_DSIG_NS_MORE_07_05);
+ } else {
+ throw new XMLSecurityException("KeyDerivation.NotSupportedParameter", new Object[] {kdfAlgorithm});
+ }
+ return kdfParams;
}
- public void setConcatKDFParams(ConcatKDFParamsImpl concatKDFParams) {
- this.concatKDFParams = concatKDFParams;
- appendSelf(concatKDFParams);
- addReturnToSelf();
+ public void setKDFParams(KDFParams kdfParams) {
+ this.kdfParams = kdfParams;
+ if (kdfParams instanceof ElementProxy) {
+ appendSelf((ElementProxy)kdfParams);
+ addReturnToSelf();
+ } else {
+ LOG.debug("Could not append KDFParams because it does not implement ElementProxy");
+ }
}
+
@Override
public String getBaseLocalName() {
return EncryptionConstants._TAG_KEYDERIVATIONMETHOD;
@@ -102,7 +126,7 @@ public class KeyDerivationMethodImpl extends Encryption11ElementProxy implements
@Override
public String toString() {
return new StringJoiner(", ", KeyDerivationMethodImpl.class.getSimpleName() + "[", "]")
- .add("concatKDFParams=" + concatKDFParams)
+ .add("kdfParams=" + kdfParams)
.toString();
}
}
diff --git a/src/main/java/org/apache/xml/security/encryption/params/ConcatKDFParams.java b/src/main/java/org/apache/xml/security/encryption/params/ConcatKDFParams.java
index 891c5ff5..57cefb05 100644
--- a/src/main/java/org/apache/xml/security/encryption/params/ConcatKDFParams.java
+++ b/src/main/java/org/apache/xml/security/encryption/params/ConcatKDFParams.java
@@ -22,9 +22,11 @@ import org.apache.xml.security.algorithms.MessageDigestAlgorithm;
import org.apache.xml.security.utils.EncryptionConstants;
/**
- * Class ConcatKeyDerivationParameter is used to specify parameters for the ConcatKDF key derivation algorithm.
- * @see <A HREF="https://www.w3.org/TR/xmlenc-core1/#sec-ConcatKDF">XML Encryption Syntax and Processing Version 1.1, 5.8.1
- * The ConcatKDF Key Derivation Algorithm</A>
+ * Class ConcatKDFParams is used to specify parameters for the
+ * ConcatKDF key derivation algorithm.
+ *
+ * @see <A HREF="https://www.w3.org/TR/xmlenc-core1/#sec-ConcatKDF">XML Encryption
+ * syntax and Processing Version 1.1, 5.8.1 The ConcatKDF Key Derivation Algorithm</A>
*/
public class ConcatKDFParams extends KeyDerivationParameters {
@@ -36,12 +38,12 @@ public class ConcatKDFParams extends KeyDerivationParameters {
private String suppPrivInfo;
/**
- * Constructor ConcatKeyDerivationParameter with specified digest algorithm
+ * Constructor ConcatKDFParams with specified digest algorithm
*
* @param keyBitLength the length of the derived key in bits
* @param digestAlgorithm the digest algorithm to use
*/
- public ConcatKDFParams(int keyBitLength, String digestAlgorithm) {
+ protected ConcatKDFParams(int keyBitLength, String digestAlgorithm) {
super(EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF, keyBitLength);
this.digestAlgorithm = digestAlgorithm;
}
@@ -99,4 +101,72 @@ public class ConcatKDFParams extends KeyDerivationParameters {
public void setSuppPrivInfo(String suppPrivInfo) {
this.suppPrivInfo = suppPrivInfo;
}
+
+ /**
+ * Create a new ConcatKDF key derivation algorithm parameters builder.
+ * @param keyBitLength the length of the derived key in bits
+ * @param digestAlgorithm the digest algorithm to use
+ * @return a new ConcatKDF builder to configure the key derivation parameters
+ */
+ public static Builder createBuilder(int keyBitLength, String digestAlgorithm) {
+ return new Builder(keyBitLength, digestAlgorithm);
+ }
+
+ /**
+ * The ConcatKDF key derivation algorithm parameters builder.
+ */
+ public static class Builder {
+
+ private int keyBitLength;
+ private String digestAlgorithm;
+ private String algorithmID;
+ private String partyUInfo;
+ private String partyVInfo;
+ private String suppPubInfo;
+ private String suppPrivInfo;
+
+ protected Builder(int keyBitLength, String digestAlgorithm) {
+ this.keyBitLength = keyBitLength;
+ this.digestAlgorithm = digestAlgorithm;
+ }
+
+ public Builder algorithmID(String algorithmID) {
+ this.algorithmID = algorithmID;
+ return this;
+ }
+
+ public Builder partyUInfo(String partyUInfo) {
+ this.partyUInfo = partyUInfo;
+ return this;
+ }
+
+ public Builder partyVInfo(String partyVInfo) {
+ this.partyVInfo = partyVInfo;
+ return this;
+ }
+
+ public Builder suppPubInfo(String suppPubInfo) {
+ this.suppPubInfo = suppPubInfo;
+ return this;
+ }
+
+ public Builder suppPrivInfo(String suppPrivInfo) {
+ this.suppPrivInfo = suppPrivInfo;
+ return this;
+ }
+
+ /**
+ * Method builds the ConcatKDF key derivation algorithm parameters from
+ * the builder configuration.
+ */
+ public ConcatKDFParams build() {
+ ConcatKDFParams params = new ConcatKDFParams(keyBitLength, digestAlgorithm);
+ params.setAlgorithmID(algorithmID);
+ params.setPartyUInfo(partyUInfo);
+ params.setPartyVInfo(partyVInfo);
+ params.setSuppPubInfo(suppPubInfo);
+ params.setSuppPrivInfo(suppPrivInfo);
+ return params;
+ }
+ }
}
diff --git a/src/main/java/org/apache/xml/security/encryption/params/HKDFParams.java b/src/main/java/org/apache/xml/security/encryption/params/HKDFParams.java
new file mode 100644
index 00000000..a82588d8
--- /dev/null
+++ b/src/main/java/org/apache/xml/security/encryption/params/HKDFParams.java
@@ -0,0 +1,166 @@
+/**
+ * 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.encryption.params;
+
+import org.apache.xml.security.signature.XMLSignature;
+import org.apache.xml.security.utils.EncryptionConstants;
+
+/**
+ * Class HKDFParams (HKDF parameter) is used to specify
+ * parameters for the HMAC-based Extract-and-Expand Key Derivation Function.
+ * @see <A HREF="https://datatracker.ietf.org/doc/html/rfc5869">HMAC-based
+ * Extract-and-Expand Key Derivation Function (HKDF)</A>
+ */
+public class HKDFParams extends KeyDerivationParameters {
+
+ private String hmacHashAlgorithm;
+ private byte[] salt;
+ private byte[] info;
+
+ /**
+ * Constructor HKDFParams with specified digest algorithm.
+ *
+ * @param keyBitLength the length of the derived key in bits
+ * @param hmacHashAlgorithm the HMAC hash algorithm to use for the key derivation
+ */
+ protected HKDFParams(int keyBitLength, String hmacHashAlgorithm) {
+ super(EncryptionConstants.ALGO_ID_KEYDERIVATION_HKDF, keyBitLength);
+ this.hmacHashAlgorithm = hmacHashAlgorithm;
+ }
+
+ /**
+ * Method return the digest algorithm URI. In case of algorithm is not set, the
+ * "default" algorithm http://www.w3.org/2001/04/xmldsig-more#hmac-sha256 URI
+ * algorithm is returned.
+ *
+ * @return the hmac algorithm
+ */
+ public String getHmacHashAlgorithm() {
+ return hmacHashAlgorithm == null? XMLSignature.ALGO_ID_MAC_HMAC_SHA256 : hmacHashAlgorithm;
+ }
+
+ /**
+ * Method set the digest algorithm URI.
+ *
+ * @param hmacHashAlgorithm the hmac algorithm URI
+ */
+ public void setHmacHashAlgorithm(String hmacHashAlgorithm) {
+ this.hmacHashAlgorithm = hmacHashAlgorithm;
+ }
+
+ /**
+ * Method return the salt value which is used for the key derivation.
+ *
+ * @return the salt value
+ */
+ public byte[] getSalt() {
+ return salt;
+ }
+
+ /**
+ * Method set the salt value which is used for the key derivation.
+ *
+ * @param salt
+ */
+ public void setSalt(byte[] salt) {
+ this.salt = salt;
+ }
+
+ /**
+ * Method return the info value which is used for the key derivation.
+ *
+ * @return the info value
+ */
+ public byte[] getInfo() {
+ return info;
+ }
+
+ /**
+ * Method set the info value which is used for the key derivation.
+ *
+ * @param info
+ */
+ public void setInfo(byte[] info) {
+ this.info = info;
+ }
+
+ /**
+ * Method create a new builder for the HKDFParams.
+ * @param keyBitLength the length of the derived key in bits
+ * @param hmacHashAlgorithm the HMAC hash algorithm URI to use for the key derivation
+ * @return a new builder instance
+ */
+ public static Builder createBuilder(int keyBitLength, String hmacHashAlgorithm) {
+ return new Builder(keyBitLength, hmacHashAlgorithm);
+ }
+
+ /**
+ * This class is used to create HKDF configuration parameters {@link HKDFParams}.
+ * The key length and HMAC hash algorithm are required parameters.
+ */
+ public static class Builder {
+ private final int keyBitLength;
+ private final String hmacHashAlgorithm;
+ private byte[] salt;
+ private byte[] info;
+
+ /**
+ * Constructor for the HKDFParams builder. The key bit length and HMAC hash
+ * algorithm are required parameters.
+ *
+ * @param keyBitLength the length of the derived key in bits
+ * @param hmacHashAlgorithm the HMAC hash algorithm URI to use for the key derivation
+ */
+ protected Builder(int keyBitLength, String hmacHashAlgorithm) {
+ this.keyBitLength = keyBitLength;
+ this.hmacHashAlgorithm = hmacHashAlgorithm;
+ }
+
+ /**
+ * Set the (optional) salt value which is used for the key derivation.
+ * @param salt the hkdf salt value
+ * @return the self updated builder instance
+ */
+ public Builder salt(byte[] salt) {
+ this.salt = salt;
+ return this;
+ }
+
+ /**
+ * Set the (optional) info value which is used for the key derivation.
+ * @param info the hkdf info value
+ * @return the self updated builder instance
+ */
+ public Builder info(byte[] info) {
+ this.info = info;
+ return this;
+ }
+
+ /**
+ * Build the HKDFParams instance with the configured parameters.
+ * @return the configured HKDFParams instance
+ */
+ public HKDFParams build() {
+ HKDFParams params = new HKDFParams(keyBitLength, hmacHashAlgorithm);
+ params.setSalt(salt);
+ params.setInfo(info);
+ return params;
+ }
+ }
+}
diff --git a/src/main/java/org/apache/xml/security/encryption/params/KeyDerivationParameters.java b/src/main/java/org/apache/xml/security/encryption/params/KeyDerivationParameters.java
index e22dbff8..0540057e 100644
--- a/src/main/java/org/apache/xml/security/encryption/params/KeyDerivationParameters.java
+++ b/src/main/java/org/apache/xml/security/encryption/params/KeyDerivationParameters.java
@@ -26,7 +26,7 @@ public abstract class KeyDerivationParameters {
private final String algorithm;
private final int keyBitLength;
- public KeyDerivationParameters(String algorithm, int keyLength) {
+ protected KeyDerivationParameters(String algorithm, int keyLength) {
this.algorithm = algorithm;
this.keyBitLength = keyLength;
}
@@ -35,7 +35,22 @@ public abstract class KeyDerivationParameters {
return algorithm;
}
+ /**
+ * The length of the derived key in bits.
+ * @return
+ */
public int getKeyBitLength() {
return keyBitLength;
}
+
+ /**
+ * The length of the derived key in bytes needed to store the key in bitSize.
+ * For example: if the key is 9 bits long, the length of the key in bytes is 2, but
+ * the key is stored in 8 bits the length in bytes is 1.
+
+ * @return the length of the derived key in bytes
+ */
+ public int getKeyLength() {
+ return keyBitLength / 8 + (keyBitLength % 8 == 0 ? 0 : 1);
+ }
}
diff --git a/src/main/java/org/apache/xml/security/resource/xmlsecurity_de.properties b/src/main/java/org/apache/xml/security/resource/xmlsecurity_de.properties
index 68d2aced..1c4ad669 100644
--- a/src/main/java/org/apache/xml/security/resource/xmlsecurity_de.properties
+++ b/src/main/java/org/apache/xml/security/resource/xmlsecurity_de.properties
@@ -30,7 +30,7 @@ algorithms.HMACOutputLengthMax = HMACOutputLength darf nicht grosser als {0} sei
algorithms.HMACOutputLengthMin = HMACOutputLength darf nicht kleiner als {0} sein
algorithms.HMACOutputLengthOnlyForHMAC = Die HMACOutputLength kann nur bei HMAC integrit\u00e4ts Algorithmen angegeben werden
algorithms.MissingRSAPSSParams = RSAPSSParams is a required Element for http://www.w3.org/2007/05/xmldsig-more#rsa-pss
-algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verf\u00fcgbar.
+algorithms.NoSuchAlgorithmNoEx = Der Algorithmus {0} ist nicht verf\u00fcgbar.
algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verf\u00fcgbar. Original Nachricht war\: {1}
algorithms.NoSuchMap = Algorithmus URI "{0}" konnte auf keinen JCE Algorithmus gemappt werden
algorithms.NoSuchProvider = Der angegebene Provider {0} existiert nicht. Original Nachricht war\: {1}
@@ -109,9 +109,12 @@ KeyStore.alreadyRegistered = Klasse {0} bereits registriert f\u00fcr {1}
KeyStore.register = {1} type class register error in class {0}
KeyStore.registerStore.register = Registrierungsfehler f\u00fcr Typ {0}
KeyValue.IllegalArgument = Kann kein {0} aus {1} erzeugen
+KeyDerivation.MissingParameters = Schl\u00fcsselableitungsparameter m\u00fcssen null sein
KeyDerivation.TooShortParameter = Parameter zu kurz {0}
KeyDerivation.InvalidParameter = Ung\u00fcltige Parameter {0}
+KeyDerivation.InvalidParametersType = F\u00fcr den Algorithmus {0} m\u00fcssen Schl\u00fcsselableitungsparameter vom Typ {1} bereitgestellt werden.
KeyDerivation.NotSupportedParameter = Nicht unterst\u00fctzter Parameterwert {0}
+KeyDerivation.UnsupportedAlgorithm = Nicht unterst\u00fctzter Schl\u00fcsselableitungsalgorithmus: {0} f\u00fcr Klasse {1}
namespacePrefixAlreadyUsedByOtherURI = Namespace {0} wird bereits von einer anderen URI {1} gebraucht
notYetInitialized = Das Modul {0} ist noch nicht initialisiert
prefix.AlreadyAssigned = Sie binden den Prefix {0} an den Namespace {1} aber er ist bereits an {2} zugewiesen
diff --git a/src/main/java/org/apache/xml/security/resource/xmlsecurity_en.properties b/src/main/java/org/apache/xml/security/resource/xmlsecurity_en.properties
index f1b36a1b..74e8c150 100644
--- a/src/main/java/org/apache/xml/security/resource/xmlsecurity_en.properties
+++ b/src/main/java/org/apache/xml/security/resource/xmlsecurity_en.properties
@@ -109,9 +109,12 @@ KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
KeyStore.register = {1} type class register error in class {0}
KeyStore.registerStore.register = Registration error for type {0}
KeyValue.IllegalArgument = Cannot create a {0} from {1}
+KeyDerivation.MissingParameters = Key derivation parameters must not be null
KeyDerivation.TooShortParameter = Key derivation parameter {0} is too short
KeyDerivation.InvalidParameter = Key derivation parameter {0} is illegal
+KeyDerivation.InvalidParametersType = Algorithm {0} requires key derivation parameters of type {1} to be provided
KeyDerivation.NotSupportedParameter = Key derivation parameter {0} is not supported
+KeyDerivation.UnsupportedAlgorithm = Unsupported key derivation algorithm {0} for class {1}
namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1}
notYetInitialized = The module {0} is not yet initialized
prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2}
@@ -132,7 +135,7 @@ signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug?
signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0}
signature.Transform.XPathError = Error evaluating XPath expression
signature.Transform.node = Current Node: {0}
-signature.Transform.nodeAndType = Current Node: {0}, type: {1}
+signature.Transform.nodeAndType = Current Node: {0}, type: {1}
signature.Util.BignumNonPositive = bigInteger.signum() must be positive
signature.Util.NonTextNode = Not a text node
signature.Util.TooManyChilds = Too many childs of Type {0} in {1}
diff --git a/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityUtils.java b/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityUtils.java
index b0c3a35d..ec4a9f6a 100644
--- a/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityUtils.java
+++ b/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityUtils.java
@@ -522,12 +522,23 @@ public class XMLSecurityUtils {
concreteLSInput.setByteStream(
ClassLoaderUtils.getResourceAsStream("bindings/schemas/xml.xsd", XMLSecurityConstants.class));
return concreteLSInput;
- } else if ("rsa-pss.xsd".equals(systemId)) {
+ } else if ("dsig-more_2001_04.xsd".equals(systemId)) {
ConcreteLSInput concreteLSInput = new ConcreteLSInput();
concreteLSInput.setByteStream(
- ClassLoaderUtils.getResourceAsStream("bindings/schemas/rsa-pss.xsd", XMLSecurityConstants.class));
+ ClassLoaderUtils.getResourceAsStream("bindings/schemas/dsig-more_2001_04.xsd", XMLSecurityConstants.class));
+ return concreteLSInput;
+ } else if ("dsig-more_2007_05.xsd".equals(systemId)) {
+ ConcreteLSInput concreteLSInput = new ConcreteLSInput();
+ concreteLSInput.setByteStream(
+ ClassLoaderUtils.getResourceAsStream("bindings/schemas/dsig-more_2007_05.xsd", XMLSecurityConstants.class));
+ return concreteLSInput;
+ } else if ("dsig-more_2021_04.xsd".equals(systemId)) {
+ ConcreteLSInput concreteLSInput = new ConcreteLSInput();
+ concreteLSInput.setByteStream(
+ ClassLoaderUtils.getResourceAsStream("bindings/schemas/dsig-more_2021_04.xsd", XMLSecurityConstants.class));
return concreteLSInput;
}
+
return null;
}
});
@@ -539,7 +550,9 @@ public class XMLSecurityUtils {
new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xenc-schema.xsd", XMLSecurityConstants.class)),
new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xenc-schema-11.xsd", XMLSecurityConstants.class)),
new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xmldsig11-schema.xsd", XMLSecurityConstants.class)),
- new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/rsa-pss.xsd", XMLSecurityConstants.class))
+ new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/dsig-more_2001_04.xsd", XMLSecurityConstants.class)),
+ new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/dsig-more_2007_05.xsd", XMLSecurityConstants.class)),
+ new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/dsig-more_2021_04.xsd", XMLSecurityConstants.class))
}
);
return schema;
diff --git a/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractSignatureInputHandler.java b/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractSignatureInputHandler.java
index 68dc7686..dd69ee2f 100644
--- a/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractSignatureInputHandler.java
+++ b/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractSignatureInputHandler.java
@@ -50,7 +50,7 @@ import org.apache.xml.security.binding.xmldsig.CanonicalizationMethodType;
import org.apache.xml.security.binding.xmldsig.SignatureMethodType;
import org.apache.xml.security.binding.xmldsig.SignatureType;
import org.apache.xml.security.binding.xmldsig.SignedInfoType;
-import org.apache.xml.security.binding.xmldsig.pss.RSAPSSParams;
+import org.apache.xml.security.binding.xmldsigmore.RSAPSSParamsType;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.stax.ext.AbstractInputSecurityHeaderHandler;
@@ -376,10 +376,10 @@ public abstract class AbstractSignatureInputHandler extends AbstractInputSecurit
private PSSParameterSpec rsaPSSParameterSpec(SignatureType signatureType) throws XMLSecurityException {
SignatureMethodType signatureMethod = signatureType.getSignedInfo().getSignatureMethod();
- RSAPSSParams rsapssParams = null;
+ RSAPSSParamsType rsapssParams = null;
for (Object o : signatureMethod.getContent()) {
- if (o instanceof RSAPSSParams) {
- rsapssParams = (RSAPSSParams) o;
+ if (o instanceof RSAPSSParamsType) {
+ rsapssParams = (RSAPSSParamsType) o;
break;
}
}
diff --git a/src/main/java/org/apache/xml/security/utils/Constants.java b/src/main/java/org/apache/xml/security/utils/Constants.java
index 03d3770a..c894bf50 100644
--- a/src/main/java/org/apache/xml/security/utils/Constants.java
+++ b/src/main/java/org/apache/xml/security/utils/Constants.java
@@ -67,6 +67,9 @@ public final class Constants {
/** The (newer) URL for more algorithms **/
public static final String XML_DSIG_NS_MORE_07_05 = "http://www.w3.org/2007/05/xmldsig-more#";
+ /** The 2021 xmldsig-more URL for Internet Engineering Task Force (IETF) algorithms **/
+ public static final String XML_DSIG_NS_MORE_21_04 = "http://www.w3.org/2021/04/xmldsig-more#";
+
/** The URI for XML spec*/
public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace";
@@ -137,6 +140,9 @@ public final class Constants {
/** Tag of Element RSAPSSParams **/
public static final String _TAG_RSAPSSPARAMS = "RSAPSSParams";
+ /** Tag of Element Salt **/
+ public static final String _TAG_SALT = "Salt";
+
/** Tag of Element SaltLength **/
public static final String _TAG_SALTLENGTH = "SaltLength";
diff --git a/src/main/java/org/apache/xml/security/utils/DERDecoderUtils.java b/src/main/java/org/apache/xml/security/utils/DERDecoderUtils.java
index 80812ad4..3de09d29 100644
--- a/src/main/java/org/apache/xml/security/utils/DERDecoderUtils.java
+++ b/src/main/java/org/apache/xml/security/utils/DERDecoderUtils.java
@@ -6,9 +6,9 @@
* 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
- * <p>
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- * <p>
+ *
* 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
@@ -196,7 +196,6 @@ public class DERDecoderUtils {
return new BigInteger(1, intSizeBytes).intValue();
}
-
/**
* The first two nodes of the OID are encoded onto a single byte.
* The first node is multiplied by the decimal 40 and the result is added to the value of the second node.
diff --git a/src/main/java/org/apache/xml/security/utils/ElementProxy.java b/src/main/java/org/apache/xml/security/utils/ElementProxy.java
index a3edd35f..74f6d125 100644
--- a/src/main/java/org/apache/xml/security/utils/ElementProxy.java
+++ b/src/main/java/org/apache/xml/security/utils/ElementProxy.java
@@ -508,6 +508,9 @@ public abstract class ElementProxy {
"http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter", "xx"
);
setNamespacePrefix("http://www.w3.org/2009/xmldsig11#", "dsig11");
+ setNamespacePrefix("http://www.w3.org/2001/04/xmldsig-more", "rfc4051");
+ setNamespacePrefix("http://www.w3.org/2007/05/xmldsig-more#", "rfc6931");
+ setNamespacePrefix("http://www.w3.org/2021/04/xmldsig-more#", "rfc9231");
}
/**
diff --git a/src/main/java/org/apache/xml/security/utils/EncryptionConstants.java b/src/main/java/org/apache/xml/security/utils/EncryptionConstants.java
index 284e43a6..c752c042 100644
--- a/src/main/java/org/apache/xml/security/utils/EncryptionConstants.java
+++ b/src/main/java/org/apache/xml/security/utils/EncryptionConstants.java
@@ -60,7 +60,6 @@ public final class EncryptionConstants {
/** Tag of Attr PartyVInfo**/
public static final String _ATT_SUPPPRIVINFO = "SuppPrivInfo";
-
/** Tag of Element CarriedKeyName **/
public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName";
@@ -127,6 +126,18 @@ public final class EncryptionConstants {
/** Tag of Element ConcatKDFParams **/
public static final String _TAG_CONCATKDFPARAMS = "ConcatKDFParams";
+ /** Tag of Element HKDFParams **/
+ public static final String _TAG_HKDFPARAMS = "HKDFParams";
+
+ /** Tag of Element PRF pseudorandom function (PRF) **/
+ public static final String _TAG_PRF = "PRF";
+
+ /** Tag of Element Info **/
+ public static final String _TAG_INFO = "Info";
+
+ /** Tag of Element KEY LENGTH **/
+ public static final String _TAG_KEYLENGTH = "KeyLength";
+
/** Field ENCRYPTIONSPECIFICATION_URL */
public static final String ENCRYPTIONSPECIFICATION_URL =
"http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/";
@@ -217,6 +228,12 @@ public final class EncryptionConstants {
public static final String ALGO_ID_KEYAGREEMENT_ECDH_ES =
EncryptionConstants.EncryptionSpec11NS + "ECDH-ES";
+ public static final String ALGO_ID_KEYAGREEMENT_X25519 =
+ Constants.XML_DSIG_NS_MORE_21_04 + "x25519";
+
+ public static final String ALGO_ID_KEYAGREEMENT_X448 =
+ Constants.XML_DSIG_NS_MORE_21_04 + "x448";
+
/** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */
public static final String ALGO_ID_KEYWRAP_TRIPLEDES =
EncryptionConstants.EncryptionSpecNS + "kw-tripledes";
@@ -289,6 +306,10 @@ public final class EncryptionConstants {
public static final String ALGO_ID_KEYDERIVATION_CONCATKDF =
EncryptionConstants.EncryptionSpec11NS + "ConcatKDF";
+ /** Key derivation function HKDF */
+ public static final String ALGO_ID_KEYDERIVATION_HKDF =
+ Constants.XML_DSIG_NS_MORE_21_04 + "hkdf";
+
private EncryptionConstants() {
// we don't allow instantiation
}
diff --git a/src/main/java/org/apache/xml/security/utils/KeyUtils.java b/src/main/java/org/apache/xml/security/utils/KeyUtils.java
index 37247a75..a0963eed 100644
--- a/src/main/java/org/apache/xml/security/utils/KeyUtils.java
+++ b/src/main/java/org/apache/xml/security/utils/KeyUtils.java
@@ -20,14 +20,17 @@ package org.apache.xml.security.utils;
import org.apache.xml.security.algorithms.implementations.ECDSAUtils;
import org.apache.xml.security.encryption.XMLEncryptionException;
+import org.apache.xml.security.encryption.keys.content.derivedKey.ConcatKDF;
+import org.apache.xml.security.encryption.keys.content.derivedKey.HKDF;
import org.apache.xml.security.encryption.params.ConcatKDFParams;
+import org.apache.xml.security.encryption.params.HKDFParams;
import org.apache.xml.security.encryption.params.KeyAgreementParameters;
import org.apache.xml.security.encryption.params.KeyDerivationParameters;
import org.apache.xml.security.exceptions.DERDecodingException;
import org.apache.xml.security.exceptions.XMLSecurityException;
-import org.apache.xml.security.encryption.keys.content.derivedKey.ConcatKDF;
-import javax.crypto.*;
+import javax.crypto.KeyAgreement;
+import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.security.interfaces.ECPublicKey;
@@ -40,6 +43,7 @@ import java.util.Arrays;
public class KeyUtils {
private static final org.slf4j.Logger LOG =
org.slf4j.LoggerFactory.getLogger(KeyUtils.class.getName());
+
/**
* Enumeration of Supported key algorithm types.
*/
@@ -107,8 +111,7 @@ public class KeyUtils {
X25519("x25519", "RFC 7748", KeyAlgorithmType.XDH, "1.3.101.110"),
X448("x448", "RFC 7748", KeyAlgorithmType.XDH, "1.3.101.111"),
ED25519("ed25519", "RFC 8032", KeyAlgorithmType.EdDSA, "1.3.101.112"),
- ED448("ed448", "RFC 8032", KeyAlgorithmType.EdDSA, "1.3.101.113"),
- ;
+ ED448("ed448", "RFC 8032", KeyAlgorithmType.EdDSA, "1.3.101.113");
private final String name;
private final String origin;
@@ -122,7 +125,6 @@ public class KeyUtils {
this.oid = oid;
}
-
public String getName() {
return name;
}
@@ -171,9 +173,8 @@ public class KeyUtils {
} else {
String keyOId = DERDecoderUtils.getAlgorithmIdFromPublicKey(recipientPublicKey);
KeyType keyType = KeyType.getByOid(keyOId);
- keyPairGenerator = createKeyPairGenerator(keyType==null?keyOId: keyType.getName() , provider);
+ keyPairGenerator = createKeyPairGenerator(keyType == null ? keyOId : keyType.getName(), provider);
}
-
return keyPairGenerator.generateKeyPair();
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | DERDecodingException e) {
throw new XMLEncryptionException(e);
@@ -193,7 +194,6 @@ public class KeyUtils {
: KeyPairGenerator.getInstance(algorithm, provider);
}
-
/**
* Method generates a secret key for given KeyAgreementParameterSpec.
*
@@ -220,8 +220,6 @@ public class KeyUtils {
byte[] secret = keyAgreement.generateSecret();
byte[] kek = deriveKeyEncryptionKey(secret, parameterSpec.getKeyDerivationParameter());
return new SecretKeySpec(kek, "AES");
-
-
} catch (XMLSecurityException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new XMLEncryptionException(e);
}
@@ -247,34 +245,76 @@ public class KeyUtils {
}
}
-
/**
- * Derive a key encryption key from a shared secret and keyDerivationParameter. Currently only the ConcatKDF is supported.
+ * Derive a key encryption key from a shared secret and keyDerivationParameter.
+ * Currently only the ConcatKDF and HMAC-base Extract-and-Expand Key Derivation
+ * Function (HKDF) are supported.
+ *
* @param sharedSecret the shared secret
* @param keyDerivationParameter the key derivation parameters
* @return the derived key encryption key
+ * @throws IllegalArgumentException if the keyDerivationParameter is null
* @throws XMLSecurityException if the key derivation algorithm is not supported
*/
public static byte[] deriveKeyEncryptionKey(byte[] sharedSecret, KeyDerivationParameters keyDerivationParameter)
throws XMLSecurityException {
- int iKeySize = keyDerivationParameter.getKeyBitLength()/8;
+
+ if (keyDerivationParameter == null) {
+ throw new IllegalArgumentException(I18n.translate("KeyDerivation.MissingParameters"));
+ }
+
String keyDerivationAlgorithm = keyDerivationParameter.getAlgorithm();
- if (!EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF.equals(keyDerivationAlgorithm)) {
- throw new XMLEncryptionException( "unknownAlgorithm",
- keyDerivationAlgorithm);
+ if (keyDerivationParameter instanceof HKDFParams) {
+ return deriveKeyWithHKDF(sharedSecret, (HKDFParams) keyDerivationParameter);
+ } else if (keyDerivationParameter instanceof ConcatKDFParams) {
+ return deriveKeyWithConcatKDF(sharedSecret, (ConcatKDFParams) keyDerivationParameter);
+ }
+
+ throw new XMLEncryptionException("KeyDerivation.UnsupportedAlgorithm", keyDerivationAlgorithm,
+ keyDerivationParameter.getClass().getName());
+ }
+
+ /**
+ * Derive a key using the HMAC-based Extract-and-Expand Key Derivation
+ * Function (HKDF) with implementation instance {@link HKDFParams}.
+ *
+ * @param sharedSecret the shared secret
+ * @param hkdfParameter the HKDF parameters
+ * @return the derived key encryption key.
+ * @throws XMLSecurityException if the key derivation parameters are invalid or
+ * the hmac algorithm is not supported.
+ */
+ public static byte[] deriveKeyWithHKDF(byte[] sharedSecret, HKDFParams hkdfParameter)
+ throws XMLSecurityException {
+
+ if (!EncryptionConstants.ALGO_ID_KEYDERIVATION_HKDF.equals(hkdfParameter.getAlgorithm())){
+ throw new XMLEncryptionException("KeyDerivation.UnsupportedAlgorithm", hkdfParameter.getAlgorithm(),
+ HKDFParams.class.getName());
}
- ConcatKDFParams ckdfParameter = (ConcatKDFParams) keyDerivationParameter;
- // get parameters
- String digestAlgorithm = ckdfParameter.getDigestAlgorithm();
+ HKDF kdf = new HKDF();
+ return kdf.deriveKey(sharedSecret, hkdfParameter);
+ }
- String algorithmID = ckdfParameter.getAlgorithmID();
- String partyUInfo = ckdfParameter.getPartyUInfo();
- String partyVInfo = ckdfParameter.getPartyVInfo();
- String suppPubInfo = ckdfParameter.getSuppPubInfo();
- String suppPrivInfo = ckdfParameter.getSuppPrivInfo();
+ /**
+ * Derive a key using the Concatenation Key Derivation Function (ConcatKDF)
+ * with implementation instance {@link ConcatKDFParams}.
+ *
+ * @param sharedSecret the shared secret/ input keying material
+ * @param ckdfParameter the ConcatKDF parameters
+ * @return the derived key
+ * @throws XMLSecurityException if the key derivation parameters are invalid or
+ * the hash algorithm is not supported.
+ */
+ public static byte[] deriveKeyWithConcatKDF(byte[] sharedSecret, ConcatKDFParams ckdfParameter)
+ throws XMLSecurityException {
+
+ if (!EncryptionConstants.ALGO_ID_KEYDERIVATION_CONCATKDF.equals(ckdfParameter.getAlgorithm())){
+ throw new XMLEncryptionException("KeyDerivation.UnsupportedAlgorithm", ckdfParameter.getAlgorithm(),
+ HKDFParams.class.getName());
+ }
- ConcatKDF concatKDF = new ConcatKDF(digestAlgorithm);
- return concatKDF.deriveKey(sharedSecret, algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo, iKeySize);
+ ConcatKDF concatKDF = new ConcatKDF();
+ return concatKDF.deriveKey(sharedSecret, ckdfParameter);
}
}
diff --git a/src/main/resources/bindings/dsig-more.xjb b/src/main/resources/bindings/dsig-more.xjb
new file mode 100644
index 00000000..595cbb59
--- /dev/null
+++ b/src/main/resources/bindings/dsig-more.xjb
@@ -0,0 +1,20 @@
+<bindings xmlns="https://jakarta.ee/xml/ns/jaxb"
+ xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ version="3.0">
+ <bindings schemaLocation="schemas/dsig-more_2001_04.xsd" node="/xs:schema">
+ <schemaBindings>
+ <package name="org.apache.xml.security.binding.xmldsigmore"/>
+ </schemaBindings>
+ </bindings>
+ <bindings schemaLocation="schemas/dsig-more_2007_05.xsd" node="/xs:schema">
+ <schemaBindings>
+ <package name="org.apache.xml.security.binding.xmldsigmore"/>
+ </schemaBindings>
+ </bindings>
+ <bindings schemaLocation="schemas/dsig-more_2021_04.xsd" node="/xs:schema">
+ <schemaBindings>
+ <package name="org.apache.xml.security.binding.xmldsigmore"/>
+ </schemaBindings>
+ </bindings>
+</bindings>
diff --git a/src/main/resources/bindings/rsa-pss.xjb b/src/main/resources/bindings/rsa-pss.xjb
deleted file mode 100644
index e425904c..00000000
--- a/src/main/resources/bindings/rsa-pss.xjb
+++ /dev/null
@@ -1,10 +0,0 @@
-<bindings xmlns="https://jakarta.ee/xml/ns/jaxb"
- xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
- xmlns:xs="http://www.w3.org/2001/XMLSchema"
- version="3.0">
- <bindings schemaLocation="schemas/rsa-pss.xsd">
- <schemaBindings>
- <package name="org.apache.xml.security.binding.xmldsig.pss"/>
- </schemaBindings>
- </bindings>
-</bindings>
diff --git a/src/main/resources/bindings/schemas/dsig-more_2001_04.xsd b/src/main/resources/bindings/schemas/dsig-more_2001_04.xsd
new file mode 100755
index 00000000..260c18b9
--- /dev/null
+++ b/src/main/resources/bindings/schemas/dsig-more_2001_04.xsd
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified"
+ vc:minVersion="1.1"
+ xmlns:rfc4051="http://www.w3.org/2001/04/xmldsig-more"
+ targetNamespace="http://www.w3.org/2001/04/xmldsig-more">
+
+ <!-- Added in section 3.1 of this specification -->
+
+ <xs:element name="PKCS7signedData" type="xs:base64Binary"/>
+
+</xs:schema>
diff --git a/src/main/resources/bindings/schemas/dsig-more_2007_05.xsd b/src/main/resources/bindings/schemas/dsig-more_2007_05.xsd
new file mode 100755
index 00000000..7e2a4de1
--- /dev/null
+++ b/src/main/resources/bindings/schemas/dsig-more_2007_05.xsd
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified"
+ vc:minVersion="1.1"
+ xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
+ xmlns:rfc6931="http://www.w3.org/2007/05/xmldsig-more#"
+ targetNamespace="http://www.w3.org/2007/05/xmldsig-more#">
+
+ <xs:import namespace="http://www.w3.org/2000/09/xmldsig#"
+ schemaLocation="./xmldsig-core-schema.xsd"/>
+
+ <!-- Added in section 2.3.9 -->
+
+ <xs:element name="RSAPSSParams" type="rfc6931:RSAPSSParamsType">
+ <xs:annotation>
+ <xs:documentation> Top level element that can be used in xs:any namespace="#other"
+ wildcard of ds:SignatureMethod content. </xs:documentation>
+ </xs:annotation>
+ </xs:element>
+
+ <xs:complexType name="RSAPSSParamsType">
+ <xs:sequence>
+ <xs:element ref="ds:DigestMethod" minOccurs="0"/>
+ <xs:element name="MaskGenerationFunction" type="rfc6931:MaskGenerationFunctionType"
+ minOccurs="0"/>
+ <xs:element name="SaltLength" type="xs:int" minOccurs="0"/>
+ <xs:element name="TrailerField" type="xs:int" minOccurs="0"/>
+ </xs:sequence>
+ </xs:complexType>
+
+ <xs:complexType name="MaskGenerationFunctionType">
+ <xs:sequence>
+ <xs:element ref="ds:DigestMethod" minOccurs="0"/>
+ </xs:sequence>
+ <xs:attribute name="Algorithm" type="xs:anyURI"
+ default="http://www.w3.org/2007/05/xmldsig-more#MGF1"/>
+ </xs:complexType>
+
+</xs:schema>
diff --git a/src/main/resources/bindings/schemas/dsig-more_2021_04.xsd b/src/main/resources/bindings/schemas/dsig-more_2021_04.xsd
new file mode 100755
index 00000000..8fe992bc
--- /dev/null
+++ b/src/main/resources/bindings/schemas/dsig-more_2021_04.xsd
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified"
+ vc:minVersion="1.1"
+ xmlns:rfc9231="http://www.w3.org/2021/04/xmldsig-more#"
+ xmlns:xenc11="http://www.w3.org/2009/xmlenc11#"
+ targetNamespace="http://www.w3.org/2021/04/xmldsig-more#">
+
+
+ <xs:import namespace="http://www.w3.org/2009/xmlenc11#"
+ schemaLocation="./xenc-schema-11.xsd"/>
+
+ <!-- Needed for 2.6.7 -->
+
+ <xs:element name="Nonce" type="xs:hexBinary"/>
+ <xs:element name="Counter" type="xs:hexBinary"/>
+
+ <!-- Needed for 2.6.8 -->
+
+ <xs:element name="ADD" type="xs:string"/>
+
+ <!-- Added in section 2.8.1 -->
+
+ <xs:element name="HKDFParams" type="rfc9231:HKDFParamsType"/>
+
+ <xs:complexType name="HKDFParamsType">
+ <xs:sequence>
+ <xs:element name="PRF" type="xenc11:PRFAlgorithmIdentifierType"/>
+ <xs:element name="Salt" minOccurs="0" maxOccurs="1" type="xs:base64Binary"/>
+ <xs:element name="Info" minOccurs="0" maxOccurs="1" type="xs:base64Binary"/>
+ <xs:element name="KeyLength" minOccurs="0" maxOccurs="1" type="xs:positiveInteger"/>
+ </xs:sequence>
+ </xs:complexType>
+
+</xs:schema>
diff --git a/src/main/resources/bindings/schemas/rsa-pss.xsd b/src/main/resources/bindings/schemas/rsa-pss.xsd
deleted file mode 100644
index 17d4486a..00000000
--- a/src/main/resources/bindings/schemas/rsa-pss.xsd
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Schema for XML Signatures (more types)
-http://www.w3.org/2000/09/xmldsig-more#
-Refer to RFC 6931 2.3.9 [1].
-[1] https://tools.ietf.org/html/rfc6931
--->
-
-<schema xmlns="http://www.w3.org/2001/XMLSchema"
- xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
- xmlns:dsm="http://www.w3.org/2007/05/xmldsig-more#"
- targetNamespace="http://www.w3.org/2007/05/xmldsig-more#"
- version="0.1" elementFormDefault="qualified">
-
- <import namespace="http://www.w3.org/2000/09/xmldsig#"
- schemaLocation="xmldsig-core-schema.xsd" />
-
- <element name="RSAPSSParams">
- <annotation>
- <documentation>
- Top level element that can be used in xs:any namespace="#other"
- wildcard of ds:SignatureMethod content.
- </documentation>
- </annotation>
- <complexType>
- <complexContent>
- <extension base="dsm:RSAPSSParamsType">
- <sequence />
- </extension>
- </complexContent>
- </complexType>
- </element>
- <complexType name="RSAPSSParamsType">
- <sequence>
- <element ref="ds:DigestMethod" minOccurs="0"/>
- <element name="MaskGenerationFunction"
- type="dsm:MaskGenerationFunctionType" minOccurs="0"/>
- <element name="SaltLength" type="int"
- minOccurs="0"/>
- <element name="TrailerField" type="int"
- minOccurs="0"/>
- </sequence>
- </complexType>
-
- <complexType name="MaskGenerationFunctionType">
- <sequence>
- <element ref="ds:DigestMethod" minOccurs="0"/>
- </sequence>
- <attribute name="Algorithm" type="anyURI"
- default="http://www.w3.org/2007/05/xmldsig-more#MGF1"/>
- </complexType>
-
-</schema>
diff --git a/src/test/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDFTest.java b/src/test/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDFTest.java
new file mode 100644
index 00000000..67391954
--- /dev/null
+++ b/src/test/java/org/apache/xml/security/encryption/keys/content/derivedKey/HKDFTest.java
@@ -0,0 +1,173 @@
+/**
+ * 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.encryption.keys.content.derivedKey;
+
+
+import org.apache.xml.security.encryption.params.HKDFParams;
+import org.apache.xml.security.exceptions.XMLSecurityException;
+import org.apache.xml.security.signature.XMLSignature;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import javax.xml.crypto.dsig.DigestMethod;
+
+import static org.apache.xml.security.encryption.XMLCipherUtil.hexStringToByteArray;
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * The HMAC-based Extract-and-Expand Key Derivation Function (HKDF) tests as defined
+ * in RFC 5869, Appendix A. Test Vectors
+ */
+class HKDFTest {
+ private static final org.slf4j.Logger LOG =
+ org.slf4j.LoggerFactory.getLogger(HKDFTest.class);
+
+ static {
+ org.apache.xml.security.Init.init();
+ }
+
+ @ParameterizedTest(name = "{index}. {0}")
+ @CsvSource({
+ "'Rfc5869: Test Case 1','http://www.w3.org/2001/04/xmlenc#sha256'," +
+ "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b," +
+ "000102030405060708090a0b0c,f0f1f2f3f4f5f6f7f8f9,42, " +
+ "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5," +
+ "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865",
+ "'Rfc5869: Test Case 2','http://www.w3.org/2001/04/xmlenc#sha256', " +
+ "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f," +
+ "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf," +
+ "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff," +
+ "82, " +
+ "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244," +
+ "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87",
+ "'Rfc5869: Test Case 3','http://www.w3.org/2001/04/xmlenc#sha256', " +
+ "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b," +
+ "''," +
+ "''," +
+ "42, " +
+ "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04," +
+ "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8",
+ "'Rfc5869: Test Case 4','http://www.w3.org/2000/09/xmldsig#sha1', " +
+ "0b0b0b0b0b0b0b0b0b0b0b," +
+ "000102030405060708090a0b0c," +
+ "f0f1f2f3f4f5f6f7f8f9," +
+ "42, " +
+ "9b6c18c432a7bf8f0e71c8eb88f4b30baa2ba243," +
+ "085a01ea1b10f36933068b56efa5ad81a4f14b822f5b091568a9cdd4f155fda2c22e422478d305f3f896",
+ "'Rfc5869: Test Case 5','http://www.w3.org/2000/09/xmldsig#sha1', " +
+ "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f," +
+ "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf," +
+ "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff," +
+ "82, " +
+ "8adae09a2a307059478d309b26c4115a224cfaf6," +
+ "0bd770a74d1160f7c9f12cd5912a06ebff6adcae899d92191fe4305673ba2ffe8fa3f1a4e5ad79f3f334b3b202b2173c486ea37ce3d397ed034c7f9dfeb15c5e927336d0441f4c4300e2cff0d0900b52d3b4",
+ "'Rfc5869: Test Case 6','http://www.w3.org/2000/09/xmldsig#sha1', " +
+ "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b," +
+ "''," +
+ "''," +
+ "42, " +
+ "da8c8a73c7fa77288ec6f5e7c297786aa0d32d01," +
+ "0ac1af7002b3d761d1e55298da9d0506b9ae52057220a306e07b6b87e8df21d0ea00033de03984d34918",
+ "'Rfc5869: Test Case 7','http://www.w3.org/2000/09/xmldsig#sha1', " +
+ "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c," +
+ "," +
+ "''," +
+ "42, " +
+ "2adccada18779e7c2077ad2eb19d3f3e731385dd," +
+ "2c91117204d745f3500d636a62f64f0ab3bae548aa53d423b0d1f27ebba6f5e5673a081d70cce7acfc48",
+ })
+ void deriveKey(String name, String hash, String ikm, String salt, String info, int length, String prk, String okm) throws XMLSecurityException {
+ LOG.debug("Execute HKDF Test Case: [{0}]", name);
+ byte[] saltBytes = hexStringToByteArray(salt);
+ byte[] infoBytes = hexStringToByteArray(info);
+ byte[] ikmBytes = hexStringToByteArray(ikm);
+
+ byte[] expectedPRK = hexStringToByteArray(prk);
+ byte[] expectedOKM = hexStringToByteArray(okm);
+ String hmacJCEName = getHMacHashForHashJCEName(hash);
+ String hMacHashAlgorithmURI = getHMacHashForHashUri(hash);
+
+ HKDFParams params = HKDFParams.createBuilder(length * 8, hMacHashAlgorithmURI)
+ .salt(saltBytes)
+ .info(infoBytes)
+ .build();
+
+ HKDF testInstance = new HKDF();
+ byte[] extractedKey = testInstance.extractKey(hmacJCEName, saltBytes, ikmBytes);
+ byte[] derivedKey = testInstance.deriveKey(ikmBytes, params);
+
+ assertArrayEquals(expectedPRK, extractedKey);
+ assertArrayEquals(expectedOKM, derivedKey);
+ }
+
+ /**
+ * Helper method to get corresponding MacHash algorithm URI for the given hash algorithm URI.
+ *
+ * @param hashAlgorithm the hash algorithm URI
+ * @return the MacHash algorithm URI value.
+ * @throws IllegalArgumentException if the hash algorithm is not supported.
+ */
+ private static String getHMacHashForHashUri(String hashAlgorithm) {
+
+ switch (hashAlgorithm) {
+ case DigestMethod.SHA1:
+ return XMLSignature.ALGO_ID_MAC_HMAC_SHA1;
+ case "http://www.w3.org/2001/04/xmldsig-more#sha224":
+ return XMLSignature.ALGO_ID_MAC_HMAC_SHA224;
+ case DigestMethod.SHA256:
+ return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
+ case "http://www.w3.org/2001/04/xmldsig-more#sha384":
+ return XMLSignature.ALGO_ID_MAC_HMAC_SHA384;
+ case DigestMethod.SHA512:
+ return XMLSignature.ALGO_ID_MAC_HMAC_SHA512;
+ case DigestMethod.RIPEMD160:
+ return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
+ default:
+ throw new IllegalArgumentException("Unknown/not supported hash algorithm: [" + hashAlgorithm + "] for MacHash algorithm");
+ }
+ }
+
+ /**
+ * Helper method to get corresponding MacHash JCE algorithm name for the
+ * given hash algorithm URI.
+ *
+ * @param hashAlgorithm the hash algorithm URI
+ * @return the MacHash algorithm URI value.
+ * @throws IllegalArgumentException if the hash algorithm is not supported.
+ */
+ private static String getHMacHashForHashJCEName(String hashAlgorithm) {
+
+ switch (hashAlgorithm) {
+ case DigestMethod.SHA1:
+ return "HmacSHA1";
+ case "http://www.w3.org/2001/04/xmldsig-more#sha224":
+ return "HmacSHA224";
+ case DigestMethod.SHA256:
+ return "HmacSHA256";
+ case "http://www.w3.org/2001/04/xmldsig-more#sha384":
+ return "HmacSHA384";
+ case DigestMethod.SHA512:
+ return "HmacSHA512";
+ case DigestMethod.RIPEMD160:
+ return "HmacRIPEMD160";
+ default:
+ throw new IllegalArgumentException("Unknown/not supported hash algorithm: [" + hashAlgorithm + "] for MacHash algorithm");
+ }
+ }
+}
diff --git a/src/test/java/org/apache/xml/security/test/dom/encryption/XMLCipherBrainpoolTest.java b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLCipherBrainpoolTest.java
index 45c7f167..36a01b4c 100644
--- a/src/test/java/org/apache/xml/security/test/dom/encryption/XMLCipherBrainpoolTest.java
+++ b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLCipherBrainpoolTest.java
@@ -182,8 +182,9 @@ class XMLCipherBrainpoolTest {
cipherEncKey.setSecureValidation(true);
// create key agreement parameters
int keyBitLen = KeyUtils.getAESKeyBitSizeForWrapAlgorithm(keyWrapAlgorithm);
- KeyDerivationParameters keyDerivationParameter = new ConcatKDFParams(keyBitLen,
- MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256);
+ KeyDerivationParameters keyDerivationParameter = ConcatKDFParams
+ .createBuilder(keyBitLen, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256)
+ .build();
AlgorithmParameterSpec parameterSpec = new KeyAgreementParameters(
KeyAgreementParameters.ActorType.ORIGINATOR,
EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES,
diff --git a/src/test/java/org/apache/xml/security/test/dom/encryption/XMLCipherTest.java b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLCipherTest.java
index 711a1e12..2e1fa292 100644
--- a/src/test/java/org/apache/xml/security/test/dom/encryption/XMLCipherTest.java
+++ b/src/test/java/org/apache/xml/security/test/dom/encryption/XMLCipherTest.java
@@ -52,10 +52,13 @@ import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.encryption.XMLCipherUtil;
import org.apache.xml.security.encryption.keys.KeyInfoEnc;
import org.apache.xml.security.encryption.params.ConcatKDFParams;
+import org.apache.xml.security.encryption.params.HKDFParams;
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.KeyName;
import org.apache.xml.security.parser.XMLParserException;
+import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.stax.ext.XMLSecurityConstants;
import org.apache.xml.security.test.dom.TestUtils;
import org.apache.xml.security.testutils.JDKTestUtils;
@@ -298,14 +301,26 @@ public class XMLCipherTest {
void testAES128ElementEcdhEsKWCipher(KeyUtils.KeyType keyType) throws Exception {
// Skip test for IBM JDK
Assumptions.assumeTrue(haveISOPadding,
- "Test testAES128ElementEcdhEsKWCipher for key ["+keyType+"] was skipped as necessary algorithms not available!" );
+ "Test testAES128ElementEcdhEsKWCipher for key [" + keyType + "] was skipped as necessary algorithms not available!");
Assumptions.assumeTrue(JDKTestUtils.isAlgorithmSupported(keyType.getAlgorithm().getJceName(), true),
- "Test testAES128ElementEcdhEsKWCipher for key ["+keyType+"] was skipped as necessary algorithms not available!" );
+ "Test testAES128ElementEcdhEsKWCipher for key [" + keyType + "] was skipped as necessary algorithms not available!");
// init parameters encrypted key object
String dataEncryptionAlgorithm = XMLCipher.AES_256_GCM;
String keyWrapAlgorithm = XMLCipher.AES_128_KeyWrap;
int transportKeyBitLength = 128;
+ String keyAgreementMethod;
+ switch (keyType) {
+ case X25519:
+ keyAgreementMethod = EncryptionConstants.ALGO_ID_KEYAGREEMENT_X25519;
+ break;
+ case X448:
+ keyAgreementMethod = EncryptionConstants.ALGO_ID_KEYAGREEMENT_X448;
+ break;
+ default:
+ keyAgreementMethod = EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES;
+ break;
+ }
// prepare the test document
Document d = document(); // source
@@ -334,11 +349,13 @@ public class XMLCipherTest {
cipherEncKey.setSecureValidation(true);
// create key agreement parameters
int keyBitLen = KeyUtils.getAESKeyBitSizeForWrapAlgorithm(keyWrapAlgorithm);
- KeyDerivationParameters keyDerivationParameter = new ConcatKDFParams(keyBitLen,
- MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256);
+ KeyDerivationParameters keyDerivationParameter = ConcatKDFParams
+ .createBuilder(keyBitLen, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256)
+ .build();
+
AlgorithmParameterSpec parameterSpec = new KeyAgreementParameters(
KeyAgreementParameters.ActorType.ORIGINATOR,
- EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES,
+ keyAgreementMethod,
keyDerivationParameter);
// encrypt transport key with KeyAgreement
EncryptedKey encryptedKey = cipherEncKey.encryptKey(d, ephemeralSymmetricKey, parameterSpec, null);
@@ -373,6 +390,108 @@ public class XMLCipherTest {
assertEquals(source, target);
}
+ @ParameterizedTest
+ @EnumSource(value = KeyUtils.KeyType.class, mode = EnumSource.Mode.INCLUDE,
+ names = {"SECP256R1", "SECP384R1", "SECP521R1", "X25519", "X448"})
+ void testAES128ElementEcdhEsKWCipherHKDF(KeyUtils.KeyType keyType) throws Exception {
+ // Skip test for IBM JDK
+ Assumptions.assumeTrue(haveISOPadding,
+ "Test testAES128ElementEcdhEsKWCipher for key [" + keyType + "] was skipped as necessary algorithms not available!");
+ Assumptions.assumeTrue(JDKTestUtils.isAlgorithmSupported(keyType.getAlgorithm().getJceName(), true),
+ "Test testAES128ElementEcdhEsKWCipher for key [" + keyType + "] was skipped as necessary algorithms not available!");
+
+ // init parameters encrypted key object
+ String dataEncryptionAlgorithm = XMLCipher.AES_256_GCM;
+ String keyWrapAlgorithm = XMLCipher.AES_128_KeyWrap;
+ int transportKeyBitLength = 128;
+ String keyAgreementMethod;
+ switch (keyType) {
+ case X25519:
+ keyAgreementMethod = EncryptionConstants.ALGO_ID_KEYAGREEMENT_X25519;
+ break;
+ case X448:
+ keyAgreementMethod = EncryptionConstants.ALGO_ID_KEYAGREEMENT_X448;
+ break;
+ default:
+ keyAgreementMethod = EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES;
+ break;
+ }
+
+ // prepare the test document
+ Document d = document(); // source
+ Document ed = null;
+ Document dd = null;
+ Element e = (Element) d.getElementsByTagName(element()).item(index());
+ Element ee = null;
+ String source = null;
+ String target = null;
+
+ source = toString(d);
+
+ // Generate test recipient key pair
+ KeyPair recipientKeyPair = KeyTestUtils.generateKeyPair(keyType);
+ PrivateKey privRecipientKey = recipientKeyPair.getPrivate();
+ PublicKey pubRecipientKey = recipientKeyPair.getPublic();
+
+
+ // Generate a traffic key
+ KeyGenerator keygen = KeyGenerator.getInstance("AES");
+ keygen.init(transportKeyBitLength);
+ Key ephemeralSymmetricKey = keygen.generateKey();
+
+ XMLCipher cipherEncKey = XMLCipher.getInstance(keyWrapAlgorithm);
+ cipherEncKey.init(XMLCipher.WRAP_MODE, pubRecipientKey);
+ cipherEncKey.setSecureValidation(true);
+ // create key agreement parameters
+ int keyBitLen = KeyUtils.getAESKeyBitSizeForWrapAlgorithm(keyWrapAlgorithm);
+ HKDFParams keyDerivationParameter = HKDFParams.createBuilder(keyBitLen,
+ XMLSignature.ALGO_ID_MAC_HMAC_SHA256)
+ .salt(SecureRandom.getSeed(32))
+ .info("test-info-data".getBytes(StandardCharsets.UTF_8))
+ .build();
+
+ AlgorithmParameterSpec parameterSpec = new KeyAgreementParameters(
+ KeyAgreementParameters.ActorType.ORIGINATOR,
+ keyAgreementMethod,
+ keyDerivationParameter);
+ // encrypt transport key with KeyAgreement
+ EncryptedKey encryptedKey = cipherEncKey.encryptKey(d, ephemeralSymmetricKey, parameterSpec, null);
+ assertEquals(1, ((KeyInfoEnc) encryptedKey.getKeyInfo()).lengthAgreementMethod());
+ KeyName keyName = new KeyName(d, "test-key-name");
+ ((KeyInfoEnc) encryptedKey.getKeyInfo()).itemAgreementMethod(0).getRecipientKeyInfo().add(keyName);
+
+
+ // encrypt data
+ XMLCipher cipherEncData = XMLCipher.getInstance(dataEncryptionAlgorithm);
+ cipherEncData.init(XMLCipher.ENCRYPT_MODE, ephemeralSymmetricKey);
+ EncryptedData builder = cipherEncData.getEncryptedData();
+ // add encrypted key to key info in encrypted data
+ KeyInfo builderKeyInfo = builder.getKeyInfo();
+ if (builderKeyInfo == null) {
+ builderKeyInfo = new KeyInfo(d);
+ builder.setKeyInfo(builderKeyInfo);
+ }
+ builderKeyInfo.add(encryptedKey);
+
+ ed = cipherEncData.doFinal(d, e);
+
+ org.apache.xml.security.test.javax.xml.crypto.dsig.TestUtils.validateSecurityOrEncryptionElement(ed.getDocumentElement());
+
+ Files.write(Paths.get("target", "test-ka-dh-hkdf-" + keyType.name() + ".xml"), toString(ed).getBytes());
+
+ //decrypt
+ ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
+ XMLCipher cipherDecData = XMLCipher.getInstance(dataEncryptionAlgorithm);
+ cipherDecData.init(XMLCipher.DECRYPT_MODE, null);
+ cipherDecData.setKEK(privRecipientKey);
+ cipherDecData.setSecureValidation(true);
+ dd = cipherDecData.doFinal(ed, ee);
+
+ target = toString(dd);
+ assertNotNull(target);
+ assertEquals(source, target);
+ }
+
/**
* The http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p identifier defines the
* mask generation function as the fixed value of MGF1 with SHA1. In this case
@@ -458,8 +577,9 @@ public class XMLCipherTest {
cipherEncKey.init(XMLCipher.WRAP_MODE, pubRecipientKey);
cipherEncKey.setSecureValidation(true);
// create key agreement parameters
- KeyDerivationParameters keyDerivationParameter = new ConcatKDFParams(transportKeyBitLength,
- MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256);
+ KeyDerivationParameters keyDerivationParameter = ConcatKDFParams
+ .createBuilder(transportKeyBitLength, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256)
+ .build();
KeyAgreementParameters parameterSpec = new KeyAgreementParameters(
KeyAgreementParameters.ActorType.ORIGINATOR,
EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES,
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
index c645979d..cb955cbd 100644
--- 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
@@ -120,7 +120,9 @@ class XMLEncryption11BrainpoolTest extends XMLEncryption11TestAbstract{
Key sessionKey = getSessionKey(encryptionAlgorithm);
int keyBitLen = KeyUtils.getAESKeyBitSizeForWrapAlgorithm(keyWrapAlgorithm);
- KeyDerivationParameters keyDerivationParameter = new ConcatKDFParams(keyBitLen, kdfAlgorithm);
+ KeyDerivationParameters keyDerivationParameter = ConcatKDFParams
+ .createBuilder(keyBitLen, kdfAlgorithm)
+ .build();
AlgorithmParameterSpec parameterSpec = new KeyAgreementParameters(
KeyAgreementParameters.ActorType.ORIGINATOR,
EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES,
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 c157ef13..f80b71a0 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
@@ -535,7 +535,10 @@ class XMLEncryption11Test extends XMLEncryption11TestAbstract {
int keyBitLen = KeyUtils.getAESKeyBitSizeForWrapAlgorithm(keyWrapAlgorithm);
- KeyDerivationParameters keyDerivationParameter = new ConcatKDFParams(keyBitLen, kdfAlgorithm);
+ KeyDerivationParameters keyDerivationParameter = ConcatKDFParams
+ .createBuilder(keyBitLen, kdfAlgorithm)
+ .build();
+
AlgorithmParameterSpec parameterSpec = new KeyAgreementParameters(
KeyAgreementParameters.ActorType.ORIGINATOR,
EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES,
@@ -637,7 +640,9 @@ class XMLEncryption11Test extends XMLEncryption11TestAbstract {
int keyBitLen = KeyUtils.getAESKeyBitSizeForWrapAlgorithm(keyWrapAlgorithm);
- KeyDerivationParameters keyDerivationParameter = new ConcatKDFParams(keyBitLen, kdfAlgorithm);
+ KeyDerivationParameters keyDerivationParameter = ConcatKDFParams
+ .createBuilder(keyBitLen, kdfAlgorithm)
+ .build();
AlgorithmParameterSpec parameterSpec = new KeyAgreementParameters(
KeyAgreementParameters.ActorType.ORIGINATOR,
EncryptionConstants.ALGO_ID_KEYAGREEMENT_ECDH_ES,
diff --git a/src/test/java/org/apache/xml/security/testutils/KeyTestUtils.java b/src/test/java/org/apache/xml/security/testutils/KeyTestUtils.java
index 9bb30643..893d9c54 100644
--- a/src/test/java/org/apache/xml/security/testutils/KeyTestUtils.java
+++ b/src/test/java/org/apache/xml/security/testutils/KeyTestUtils.java
@@ -136,4 +136,5 @@ public class KeyTestUtils {
public static InputStream getKeyResourceAsInputStream(String fileName) {
return KeyTestUtils.class.getResourceAsStream(KEY_RESOURCE_PATH + fileName);
}
+
}