Skip to content

Commit 6ea75d4

Browse files
rheniumtenderworks
authored andcommitted
[ruby/openssl] hmac: use EVP_PKEY_new_raw_private_key() if available
Current OpenSSL 3.0.x release has a regression with zero-length MAC keys. While this issue should be fixed in a future release of OpenSSL, we can use EVP_PKEY_new_raw_private_key() in place of the problematic EVP_PKEY_new_mac_key() to avoid the issue. OpenSSL 3.0's man page recommends using it regardless: > EVP_PKEY_new_mac_key() works in the same way as > EVP_PKEY_new_raw_private_key(). New applications should use > EVP_PKEY_new_raw_private_key() instead. Fixes ruby/openssl#369 (comment) ruby/openssl@4293f18b1f
1 parent f7660b2 commit 6ea75d4

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

ext/openssl/extconf.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ def find_openssl_library
174174

175175
# added in 1.1.1
176176
have_func("EVP_PKEY_check", evp_h)
177+
have_func("EVP_PKEY_new_raw_private_key", evp_h)
177178
have_func("SSL_CTX_set_ciphersuites", ssl_h)
178179

179180
# added in 3.0.0

ext/openssl/ossl_hmac.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,19 @@ ossl_hmac_initialize(VALUE self, VALUE key, VALUE digest)
9797

9898
GetHMAC(self, ctx);
9999
StringValue(key);
100+
#ifdef HAVE_EVP_PKEY_NEW_RAW_PRIVATE_KEY
101+
pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL,
102+
(unsigned char *)RSTRING_PTR(key),
103+
RSTRING_LENINT(key));
104+
if (!pkey)
105+
ossl_raise(eHMACError, "EVP_PKEY_new_raw_private_key");
106+
#else
100107
pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL,
101108
(unsigned char *)RSTRING_PTR(key),
102109
RSTRING_LENINT(key));
103110
if (!pkey)
104111
ossl_raise(eHMACError, "EVP_PKEY_new_mac_key");
112+
#endif
105113
if (EVP_DigestSignInit(ctx, NULL, ossl_evp_get_digestbyname(digest),
106114
NULL, pkey) != 1) {
107115
EVP_PKEY_free(pkey);

test/openssl/test_hmac.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,14 @@ def test_singleton_methods
6262
b64digest = OpenSSL::HMAC.base64digest("MD5", key, "Hi There")
6363
assert_equal "kpRyejY4uxwT9I74FYv8nQ==", b64digest
6464
end
65+
66+
def test_zero_length_key
67+
# Empty string as the key
68+
hexdigest = OpenSSL::HMAC.hexdigest("SHA256", "\0"*32, "test")
69+
assert_equal "43b0cef99265f9e34c10ea9d3501926d27b39f57c6d674561d8ba236e7a819fb", hexdigest
70+
hexdigest = OpenSSL::HMAC.hexdigest("SHA256", "", "test")
71+
assert_equal "43b0cef99265f9e34c10ea9d3501926d27b39f57c6d674561d8ba236e7a819fb", hexdigest
72+
end
6573
end
6674

6775
end

0 commit comments

Comments
 (0)