From 37173e49ef0c2155fd2cbf263cbd6a7fbb705188 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Tue, 9 Mar 2021 11:23:46 -0800 Subject: [PATCH 1/2] [AndroidCrypto] Support a zero-length salt for HMACs. Java does not support zero-length arrays in the SecretKeySpec constructor, so instead use a zero-initialized one-byte array as the key when zero bytes are provided. This fixes the failing HKDF tests, so about 40ish more tests pass with this fix. --- .../pal_hmac.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c b/src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c index 57e78e658aef61..935d62ac158fba 100644 --- a/src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c +++ b/src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c @@ -29,8 +29,21 @@ jobject CryptoNative_HmacCreate(uint8_t* key, int32_t keyLen, intptr_t type) else return FAIL; - jbyteArray keyBytes = (*env)->NewByteArray(env, keyLen); - (*env)->SetByteArrayRegion(env, keyBytes, 0, keyLen, (jbyte*)key); + jbyteArray keyBytes; + + if (key && keyLen > 0) + { + keyBytes = (*env)->NewByteArray(env, keyLen); + (*env)->SetByteArrayRegion(env, keyBytes, 0, keyLen, (jbyte*)key); + } + else + { + // Java does not support zero-length byte arrays in the SecretKeySpec type, + // so instead create an empty 1-byte length byte array that's initalized to 0. + // the HMAC algorithm pads keys with zeros until the key is block-length, + // so this effectively creates the same key as if it were a zero byte-length key. + keyBytes = (*env)->NewByteArray(env, 1); + } jobject sksObj = (*env)->NewObject(env, g_sksClass, g_sksCtor, keyBytes, macName); if (CheckJNIExceptions(env)) { From 47ab0a8344049cc8bdf897060b0f6d012a506fd6 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Tue, 9 Mar 2021 11:27:28 -0800 Subject: [PATCH 2/2] Update src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c --- .../Unix/System.Security.Cryptography.Native.Android/pal_hmac.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c b/src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c index 935d62ac158fba..33a40c0480611c 100644 --- a/src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c +++ b/src/libraries/Native/Unix/System.Security.Cryptography.Native.Android/pal_hmac.c @@ -44,6 +44,7 @@ jobject CryptoNative_HmacCreate(uint8_t* key, int32_t keyLen, intptr_t type) // so this effectively creates the same key as if it were a zero byte-length key. keyBytes = (*env)->NewByteArray(env, 1); } + jobject sksObj = (*env)->NewObject(env, g_sksClass, g_sksCtor, keyBytes, macName); if (CheckJNIExceptions(env)) {