diff --git a/src/main/java/software/pando/crypto/nacl/HKDF.java b/src/main/java/software/pando/crypto/nacl/HKDF.java index 8c6557e..59b5e06 100644 --- a/src/main/java/software/pando/crypto/nacl/HKDF.java +++ b/src/main/java/software/pando/crypto/nacl/HKDF.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 Neil Madden. + * Copyright 2022-2023 Neil Madden. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,6 +59,9 @@ final class HKDF { CryptoSecretKey extract(byte[] salt, byte[] inputKeyMaterial) { if (salt == null || salt.length == 0) { salt = new byte[saltLenBytes]; + } else { + // Clone the salt, otherwise it will be zeroed out when the HMAC key is destroyed + salt = salt.clone(); } try (var saltAsKey = hmacKey(salt)) { return hmacKey(hmac(saltAsKey, inputKeyMaterial)); diff --git a/src/test/java/software/pando/crypto/nacl/HKDFTest.java b/src/test/java/software/pando/crypto/nacl/HKDFTest.java index 36221cf..e38a8ca 100644 --- a/src/test/java/software/pando/crypto/nacl/HKDFTest.java +++ b/src/test/java/software/pando/crypto/nacl/HKDFTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 Neil Madden. + * Copyright 2022-2023 Neil Madden. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.util.Arrays; + +import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.internal.Digests.fromHex; @@ -151,4 +154,19 @@ public void shouldMatchRfc5869TestVectors(String hashAlg, String ikmHex, String assertThat(prk.getEncoded()).asHexString().isEqualToIgnoringCase(expectedPrkHex); assertThat(okm).asHexString().isEqualToIgnoringCase(outputKeyMaterialHex); } + + @Test + public void shouldNotZeroOutSaltParameter() { + // Given + byte[] salt = "Test Salt".getBytes(UTF_8); + byte[] ikm = new byte[32]; + Arrays.fill(ikm, (byte) 42); + var hkdf = new HKDF("HmacSHA256"); + + // When + hkdf.extract(salt, ikm).close(); + + // Then + assertThat(salt).asString(UTF_8).isEqualTo("Test Salt"); + } } \ No newline at end of file