diff --git a/src/main/java/com/amazonaws/encryptionsdk/CryptoAlgorithm.java b/src/main/java/com/amazonaws/encryptionsdk/CryptoAlgorithm.java
index 49c01293d..ef07235d6 100644
--- a/src/main/java/com/amazonaws/encryptionsdk/CryptoAlgorithm.java
+++ b/src/main/java/com/amazonaws/encryptionsdk/CryptoAlgorithm.java
@@ -7,6 +7,7 @@
import com.amazonaws.encryptionsdk.internal.CommittedKey;
import com.amazonaws.encryptionsdk.internal.Constants;
import com.amazonaws.encryptionsdk.internal.HmacKeyDerivationFunction;
+import com.amazonaws.encryptionsdk.internal.MacAlgorithm;
import com.amazonaws.encryptionsdk.model.CiphertextHeaders;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -342,7 +343,7 @@ private SecretKey getCommittedEncryptionKey(
private SecretKey getNonCommittedEncryptionKey(
final SecretKey dataKey, final CiphertextHeaders headers) throws InvalidKeyException {
- final String macAlgorithm;
+ final MacAlgorithm macAlgorithm;
switch (this) {
case ALG_AES_128_GCM_IV12_TAG16_NO_KDF:
@@ -353,11 +354,11 @@ private SecretKey getNonCommittedEncryptionKey(
case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256:
case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256:
case ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256:
- macAlgorithm = "HmacSHA256";
+ macAlgorithm = MacAlgorithm.HmacSHA256;
break;
case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384:
case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384:
- macAlgorithm = "HmacSHA384";
+ macAlgorithm = MacAlgorithm.HmacSHA384;
break;
default:
throw new UnsupportedOperationException("Support for " + this + " not yet built.");
diff --git a/src/main/java/com/amazonaws/encryptionsdk/internal/CommittedKey.java b/src/main/java/com/amazonaws/encryptionsdk/internal/CommittedKey.java
index fa3cd84d9..5e4163576 100644
--- a/src/main/java/com/amazonaws/encryptionsdk/internal/CommittedKey.java
+++ b/src/main/java/com/amazonaws/encryptionsdk/internal/CommittedKey.java
@@ -47,7 +47,6 @@ public byte[] getCommitment() {
private static final String RAW_DATA_FORMAT = "RAW";
private static final String HKDF_SHA_512 = "HkdfSHA512";
- private static final String HMAC_SHA_512 = "HmacSHA512";
/** Generates an encryption key along with associated commitment value. */
public static CommittedKey generate(CryptoAlgorithm alg, SecretKey dataKey, byte[] nonce)
@@ -80,10 +79,10 @@ public static CommittedKey generate(CryptoAlgorithm alg, SecretKey dataKey, byte
+ rawDataKey.length);
}
- final String macAlgorithm;
+ final MacAlgorithm macAlgorithm;
switch (alg.getKeyCommitmentAlgo_()) {
case HKDF_SHA_512:
- macAlgorithm = HMAC_SHA_512;
+ macAlgorithm = MacAlgorithm.HmacSHA512;
break;
default:
throw new UnsupportedOperationException(
diff --git a/src/main/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunction.java b/src/main/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunction.java
index 8c4f4f388..3a79e4503 100644
--- a/src/main/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunction.java
+++ b/src/main/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunction.java
@@ -19,7 +19,6 @@
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
-import java.security.Provider;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
@@ -33,7 +32,8 @@
public final class HmacKeyDerivationFunction {
private static final byte[] EMPTY_ARRAY = new byte[0];
private final String algorithm;
- private final Provider provider;
+ // One Mac for extract and every expand; init() re-keys it each time.
+ private final Mac mac;
private SecretKey prk = null;
/**
@@ -50,9 +50,23 @@ public final class HmacKeyDerivationFunction {
*/
public static HmacKeyDerivationFunction getInstance(final String algorithm)
throws NoSuchAlgorithmException {
- // Constructed specifically to sanity-test arguments.
- Mac mac = Mac.getInstance(algorithm);
- return new HmacKeyDerivationFunction(algorithm, mac.getProvider());
+ return new HmacKeyDerivationFunction(algorithm, Mac.getInstance(algorithm));
+ }
+
+ /**
+ * Returns an HmacKeyDerivationFunction object using the specified algorithm and the
+ * provider cached for it by {@link MacAlgorithm}.
+ *
+ * @param algorithm the MAC algorithm
+ * @return the new Hkdf object
+ * @throws NoSuchAlgorithmException if no Provider supports a MacSpi implementation for the
+ * specified algorithm.
+ */
+ public static HmacKeyDerivationFunction getInstance(final MacAlgorithm algorithm)
+ throws NoSuchAlgorithmException {
+ return new HmacKeyDerivationFunction(
+ algorithm.getAlgorithm(),
+ Mac.getInstance(algorithm.getAlgorithm(), algorithm.getProvider()));
}
/**
@@ -73,17 +87,16 @@ public void init(final byte[] ikm) {
* @param salt the salt used for key extraction (optional)
* @param ikm the Input Keying Material
*/
- public void init(final byte[] ikm, final byte[] salt) {
+ public synchronized void init(final byte[] ikm, final byte[] salt) {
byte[] realSalt = (salt == null) ? EMPTY_ARRAY : salt.clone();
byte[] rawKeyMaterial = EMPTY_ARRAY;
try {
- Mac extractionMac = Mac.getInstance(algorithm, provider);
if (realSalt.length == 0) {
- realSalt = new byte[extractionMac.getMacLength()];
+ realSalt = new byte[mac.getMacLength()];
Arrays.fill(realSalt, (byte) 0);
}
- extractionMac.init(new SecretKeySpec(realSalt, algorithm));
- rawKeyMaterial = extractionMac.doFinal(ikm);
+ mac.init(new SecretKeySpec(realSalt, algorithm));
+ rawKeyMaterial = mac.doFinal(ikm);
this.prk = new SecretKeySpec(rawKeyMaterial, algorithm);
} catch (GeneralSecurityException e) {
// We've already checked all of the parameters so no exceptions
@@ -94,12 +107,12 @@ public void init(final byte[] ikm, final byte[] salt) {
}
}
- private HmacKeyDerivationFunction(final String algorithm, final Provider provider) {
+ private HmacKeyDerivationFunction(final String algorithm, final Mac mac) {
isTrue(
algorithm.startsWith("Hmac"),
"Invalid algorithm " + algorithm + ". Hkdf may only be used with Hmac algorithms.");
this.algorithm = algorithm;
- this.provider = provider;
+ this.mac = mac;
}
/**
@@ -110,11 +123,12 @@ private HmacKeyDerivationFunction(final String algorithm, final Provider provide
* @return a pseudorandom key of length bytes.
* @throws IllegalStateException if this object has not been initialized
*/
- public byte[] deriveKey(final byte[] info, final int length) throws IllegalStateException {
+ public synchronized byte[] deriveKey(final byte[] info, final int length)
+ throws IllegalStateException {
isTrue(length >= 0, "Length must be a non-negative value.");
assertInitialized();
final byte[] result = new byte[length];
- Mac mac = createMac();
+ initMacWithPrk();
isTrue(
length <= 255 * mac.getMacLength(),
@@ -142,12 +156,10 @@ public byte[] deriveKey(final byte[] info, final int length) throws IllegalState
return result;
}
- private Mac createMac() {
+ private void initMacWithPrk() {
try {
- Mac mac = Mac.getInstance(algorithm, provider);
mac.init(prk);
- return mac;
- } catch (NoSuchAlgorithmException | InvalidKeyException ex) {
+ } catch (InvalidKeyException ex) {
// We've already validated that this algorithm/key is correct.
throw new RuntimeException(ex);
}
diff --git a/src/main/java/com/amazonaws/encryptionsdk/internal/MacAlgorithm.java b/src/main/java/com/amazonaws/encryptionsdk/internal/MacAlgorithm.java
new file mode 100644
index 000000000..984677e89
--- /dev/null
+++ b/src/main/java/com/amazonaws/encryptionsdk/internal/MacAlgorithm.java
@@ -0,0 +1,38 @@
+// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package com.amazonaws.encryptionsdk.internal;
+
+import java.security.NoSuchAlgorithmException;
+import java.security.Provider;
+import javax.crypto.Mac;
+
+/** HMAC algorithms used for key derivation. */
+public enum MacAlgorithm {
+ HmacSHA1("HmacSHA1"),
+ HmacSHA256("HmacSHA256"),
+ HmacSHA384("HmacSHA384"),
+ HmacSHA512("HmacSHA512");
+
+ private final String algorithm;
+ // Looked up once, because Mac.getInstance without a provider is slow.
+ // Providers registered after the first lookup are not picked up.
+ private volatile Provider provider;
+
+ MacAlgorithm(final String algorithm) {
+ this.algorithm = algorithm;
+ }
+
+ String getAlgorithm() {
+ return algorithm;
+ }
+
+ Provider getProvider() throws NoSuchAlgorithmException {
+ Provider result = provider;
+ if (result == null) {
+ result = Mac.getInstance(algorithm).getProvider();
+ provider = result;
+ }
+ return result;
+ }
+}
diff --git a/src/test/java/com/amazonaws/encryptionsdk/internal/CommittedKeyTest.java b/src/test/java/com/amazonaws/encryptionsdk/internal/CommittedKeyTest.java
index b33f0bec2..3d42996ec 100644
--- a/src/test/java/com/amazonaws/encryptionsdk/internal/CommittedKeyTest.java
+++ b/src/test/java/com/amazonaws/encryptionsdk/internal/CommittedKeyTest.java
@@ -108,7 +108,8 @@ public void testGenerateCommittedKeySmokeTest() throws Exception {
final byte[] n1 = insecureRandomBytes(32);
// Hash for HKDF is SHA-512
- final HmacKeyDerivationFunction hkdf = HmacKeyDerivationFunction.getInstance("HmacSHA512");
+ final HmacKeyDerivationFunction hkdf =
+ HmacKeyDerivationFunction.getInstance(MacAlgorithm.HmacSHA512);
// K_R (Raw keying material, a.k.a. data key) is 256 bits (32 bytes)
// Normally this needs to be cryptographically secure, but we can relax this for improved
diff --git a/src/test/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunctionTest.java b/src/test/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunctionTest.java
index 7cea2c616..82826d2f8 100644
--- a/src/test/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunctionTest.java
+++ b/src/test/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunctionTest.java
@@ -21,7 +21,7 @@ public class HmacKeyDerivationFunctionTest {
private static final testCase[] testCases =
new testCase[] {
new testCase(
- "HmacSHA256",
+ MacAlgorithm.HmacSHA256,
fromCHex(
"\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"
+ "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"),
@@ -30,7 +30,7 @@ public class HmacKeyDerivationFunctionTest {
fromHex(
"3CB25F25FAACD57A90434F64D0362F2A2D2D0A90CF1A5A4C5DB02D56ECC4C5BF34007208D5B887185865")),
new testCase(
- "HmacSHA256",
+ MacAlgorithm.HmacSHA256,
fromCHex(
"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d"
+ "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b"
@@ -60,7 +60,7 @@ public class HmacKeyDerivationFunctionTest {
+ "CC30C58179EC3E87C14C01D5C1F3434F"
+ "1D87")),
new testCase(
- "HmacSHA256",
+ MacAlgorithm.HmacSHA256,
fromCHex(
"\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"
+ "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"),
@@ -71,7 +71,7 @@ public class HmacKeyDerivationFunctionTest {
+ "B8A11F5C5EE1879EC3454E5F3C738D2D"
+ "9D201395FAA4B61A96C8")),
new testCase(
- "HmacSHA1",
+ MacAlgorithm.HmacSHA1,
fromCHex("\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"),
fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"),
fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"),
@@ -80,7 +80,7 @@ public class HmacKeyDerivationFunctionTest {
+ "A4F14B822F5B091568A9CDD4F155FDA2"
+ "C22E422478D305F3F896")),
new testCase(
- "HmacSHA1",
+ MacAlgorithm.HmacSHA1,
fromCHex(
"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d"
+ "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b"
@@ -109,7 +109,7 @@ public class HmacKeyDerivationFunctionTest {
+ "486EA37CE3D397ED034C7F9DFEB15C5E"
+ "927336D0441F4C4300E2CFF0D0900B52D3B4")),
new testCase(
- "HmacSHA1",
+ MacAlgorithm.HmacSHA1,
fromCHex(
"\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"
+ "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"),
@@ -117,7 +117,7 @@ public class HmacKeyDerivationFunctionTest {
new byte[0],
fromHex("0AC1AF7002B3D761D1E55298DA9D0506" + "B9AE52057220A306E07B6B87E8DF21D0")),
new testCase(
- "HmacSHA1",
+ MacAlgorithm.HmacSHA1,
fromCHex(
"\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c"
+ "\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c"),
@@ -183,6 +183,42 @@ public void defaultSalt() throws Exception {
assertArrayEquals(key1, key4);
}
+ @Test
+ public void stringAlgorithmMatchesEnum() throws Exception {
+ for (testCase trial : testCases) {
+ HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo.name());
+ kdf.init(trial.ikm, trial.salt);
+ assertArrayEquals(trial.expected, kdf.deriveKey(trial.info, trial.expected.length));
+ }
+ }
+
+ @Test
+ public void reusedInstanceMatchesFreshInstances() throws Exception {
+ // One instance re-keys its Mac for each step, so repeated derives and re-inits
+ // must give the same keys as a fresh instance per step.
+ testCase first = testCases[1];
+ testCase second = testCases[0];
+ byte[] otherInfo = "other".getBytes(StringUtils.UTF8);
+
+ HmacKeyDerivationFunction reused = HmacKeyDerivationFunction.getInstance(first.algo);
+ reused.init(first.ikm, first.salt);
+ byte[] firstKey = reused.deriveKey(first.info, first.expected.length);
+ byte[] firstOtherKey = reused.deriveKey(otherInfo, 32);
+ reused.init(second.ikm, second.salt);
+ byte[] secondKey = reused.deriveKey(second.info, second.expected.length);
+
+ HmacKeyDerivationFunction fresh = HmacKeyDerivationFunction.getInstance(first.algo);
+ fresh.init(first.ikm, first.salt);
+ assertArrayEquals(first.expected, firstKey);
+ assertArrayEquals(fresh.deriveKey(otherInfo, 32), firstOtherKey);
+ assertArrayEquals(second.expected, secondKey);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void rejectsNonHmacAlgorithm() throws Exception {
+ HmacKeyDerivationFunction.getInstance("PBEWithHmacSHA256");
+ }
+
private static byte[] fromHex(String data) {
byte[] result = new byte[data.length() / 2];
for (int x = 0; x < result.length; x++) {
@@ -200,13 +236,13 @@ private static byte[] fromCHex(String data) {
}
private static class testCase {
- public final String algo;
+ public final MacAlgorithm algo;
public final byte[] ikm;
public final byte[] salt;
public final byte[] info;
public final byte[] expected;
- testCase(String algo, byte[] ikm, byte[] salt, byte[] info, byte[] expected) {
+ testCase(MacAlgorithm algo, byte[] ikm, byte[] salt, byte[] info, byte[] expected) {
super();
this.algo = algo;
this.ikm = ikm;