I need to be able to use HKDF algorithm on my input key in bouncy-castle FIPS library. In usual bouncy-castle library there is this straightforward way of doing this
HKDFBytesGenerator hkdfBytesGenerator = new HKDFBytesGenerator(new SHA256Digest());
HKDFParameters hkdfParameters = new HKDFParameters(inputKey, salt, info);
hkdfBytesGenerator.init(hkdfParameters);
byte[] hkdf = new byte[32];
hkdfBytesGenerator.generateBytes(hkdf, 0, 32);
In bouncy-castle FIPS however I couldn't yet figure out how to perform the same operation. I need to be able to provide both salt
and info
parameters.
HKDFKeyBuilder#build
only performs "extraction" part without "expanding" and therefore doesn't have info
as a parameter. Similarly named HKDFBytesGenerator
however doesn't perform "extraction" and therefore doesn't contain salt
.
The answer was next to me the whole time. As I mentioned HKDFKeyBuilder
only performs "extraction" and HKDFBytesGenerator
only performs "expanding", so you need to use both. You need to first extract key with HKDFKeyBuilder
and then expand it with HKDFBytesGenerator
. The code should look similar to this depending on your other parameters
HKDFKeyBuilder hkdfKeyBuilder = FipsKDF.HKDF_KEY_BUILDER.withSalt(salt).withPrf(AgreementKDFPRF.SHA256_HMAC);
byte[] extractedKey = hkdfKeyBuilder.build(inputKey).getKey();
AgreementOperatorFactory factory = new AgreementOperatorFactory();
KDFCalculator<AgreementKDFParameters> kdfCalculator = factory.createKDFCalculator(FipsKDF.HKDF.withPRF(AgreementKDFPRF.SHA256_HMAC).using(extractedKey).withIV(info));
byte[] hkdf = new byte[32];
kdfCalculator.generateBytes(hkdf);
return hkdf;