Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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:
Expand All @@ -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.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

/**
Expand All @@ -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 <code>HmacKeyDerivationFunction</code> object using the specified algorithm and the
* provider cached for it by {@link MacAlgorithm}.
*
* @param algorithm the MAC algorithm
* @return the new <code>Hkdf</code> 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()));
}

/**
Expand All @@ -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
Expand All @@ -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;
}

/**
Expand All @@ -110,11 +123,12 @@ private HmacKeyDerivationFunction(final String algorithm, final Provider provide
* @return a pseudorandom key of <code>length</code> 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(),
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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"
Expand Down Expand Up @@ -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"),
Expand All @@ -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"),
Expand All @@ -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"
Expand Down Expand Up @@ -109,15 +109,15 @@ 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"),
new byte[0],
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"),
Expand Down Expand Up @@ -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++) {
Expand All @@ -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;
Expand Down
Loading