Skip to content

Commit 95c20b3

Browse files
fix: create AES-256 keys of the correct length with all curves (#282)
We previously output a key that was the same length as the shared secret. This isn't what we want since AES-256 always uses keys of the same length --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent 9e318bb commit 95c20b3

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

sdk/src/main/java/io/opentdf/platform/sdk/ECKeyPair.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929

3030
public class ECKeyPair {
3131

32+
private static final int SHA256_BYTES = 32;
33+
3234
static {
3335
Security.addProvider(new BouncyCastleProvider());
3436
}
@@ -233,8 +235,12 @@ public static byte[] computeECDHKey(ECPublicKey publicKey, ECPrivateKey privateK
233235
}
234236
}
235237

238+
/**
239+
* Returns a HKDF key derived from the provided salt and secret
240+
* that is 32 bytes (256 bits) long.
241+
*/
236242
public static byte[] calculateHKDF(byte[] salt, byte[] secret) {
237-
byte[] key = new byte[secret.length];
243+
byte[] key = new byte[SHA256_BYTES];
238244
HKDFParameters params = new HKDFParameters(secret, salt, null);
239245

240246
HKDFBytesGenerator hkdf = new HKDFBytesGenerator(SHA256Digest.newInstance());

sdk/src/test/java/io/opentdf/platform/sdk/ECKeyPairTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import java.util.Base64;
1414

1515
import static io.opentdf.platform.sdk.NanoTDFType.ECCurve.SECP256R1;
16+
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
1617
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
1718
import static org.junit.jupiter.api.Assertions.assertEquals;
1819

@@ -117,6 +118,19 @@ void extractPemPubKeyFromX509() throws CertificateException, IOException, NoSuch
117118
byte[] key = ECKeyPair.calculateHKDF(ECKeys.salt.getBytes(StandardCharsets.UTF_8), symmetricKey);
118119
System.out.println(Arrays.toString(key));
119120
System.out.println(key.length);
121+
122+
assertThat(key.length).isEqualTo(32); // SHA-256 produces a 32-byte key
123+
}
124+
125+
@Test
126+
void createSymmetricKeysWithOtherCurves() {
127+
ECKeyPair pubPair = new ECKeyPair(NanoTDFType.ECCurve.SECP384R1, ECKeyPair.ECAlgorithm.ECDH);
128+
ECKeyPair keyPair = new ECKeyPair(NanoTDFType.ECCurve.SECP384R1, ECKeyPair.ECAlgorithm.ECDH);
129+
130+
byte[] sharedSecret = ECKeyPair.computeECDHKey(pubPair.getPublicKey(), keyPair.getPrivateKey());
131+
byte[] encryptionKey = ECKeyPair.calculateHKDF(ECKeys.salt.getBytes(StandardCharsets.UTF_8), sharedSecret);
132+
133+
assertThat(encryptionKey).hasSize(32); // SHA-256 produces a 32-byte key
120134
}
121135

122136
@Test

0 commit comments

Comments
 (0)