1 # frozen_string_literal: true
2 require_relative 'utils'
6 class OpenSSL::TestHMAC < OpenSSL::TestCase
8 # RFC 2202 2. Test Cases for HMAC-MD5
9 hmac = OpenSSL::HMAC.new(["0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"].pack("H*"), "MD5")
10 hmac.update("Hi There")
11 assert_equal ["9294727a3638bb1c13f48ef8158bfc9d"].pack("H*"), hmac.digest
12 assert_equal "9294727a3638bb1c13f48ef8158bfc9d", hmac.hexdigest
13 assert_equal "kpRyejY4uxwT9I74FYv8nQ==", hmac.base64digest
15 # RFC 4231 4.2. Test Case 1
16 hmac = OpenSSL::HMAC.new(["0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"].pack("H*"), "SHA224")
17 hmac.update("Hi There")
18 assert_equal ["896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22"].pack("H*"), hmac.digest
19 assert_equal "896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22", hmac.hexdigest
20 assert_equal "iW+xEoq73xloMhB81J3zP0e0sRaZErpPU2hLIg==", hmac.base64digest
24 pend "HMAC#initialize_copy is currently broken on OpenSSL 3.0.0" if openssl?(3, 0, 0)
25 h1 = OpenSSL::HMAC.new("KEY", "MD5")
28 assert_equal(h1.digest, h.digest, "dup digest")
31 def test_binary_update
32 data = "Lücíllé: Bût... yøü sáîd hé wås âlrîght.\nDr. Físhmån: Yés. Hé's løst hîs léft hånd, sø hé's gøîng tø bé åll rîght"
33 hmac = OpenSSL::HMAC.new("qShkcwN92rsM9nHfdnP4ugcVU2iI7iM/trovs01ZWok", "SHA256")
34 result = hmac.update(data).hexdigest
35 assert_equal "a13984b929a07912e4e21c5720876a8e150d6f67f854437206e7f86547248396", result
38 def test_reset_keep_key
39 h1 = OpenSSL::HMAC.new("KEY", "MD5")
40 first = h1.update("test").hexdigest
42 second = h1.update("test").hexdigest
43 assert_equal first, second
47 h1 = OpenSSL::HMAC.new("KEY", "MD5")
48 h2 = OpenSSL::HMAC.new("KEY", OpenSSL::Digest.new("MD5"))
49 h3 = OpenSSL::HMAC.new("FOO", "MD5")
52 refute_equal h1, h2.digest
56 def test_singleton_methods
57 # RFC 2202 2. Test Cases for HMAC-MD5
58 key = ["0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"].pack("H*")
59 digest = OpenSSL::HMAC.digest("MD5", key, "Hi There")
60 assert_equal ["9294727a3638bb1c13f48ef8158bfc9d"].pack("H*"), digest
61 hexdigest = OpenSSL::HMAC.hexdigest("MD5", key, "Hi There")
62 assert_equal "9294727a3638bb1c13f48ef8158bfc9d", hexdigest
63 b64digest = OpenSSL::HMAC.base64digest("MD5", key, "Hi There")
64 assert_equal "kpRyejY4uxwT9I74FYv8nQ==", b64digest