Skip to content

Commit a36220b

Browse files
authored
Merge pull request #381 from rhenium/ky/hmac-base64
hmac: implement base64digest methods
2 parents 3d16091 + 098bcb6 commit a36220b

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lib/openssl/hmac.rb

+25
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ def ==(other)
1010
OpenSSL.fixed_length_secure_compare(self.digest, other.digest)
1111
end
1212

13+
# :call-seq:
14+
# hmac.base64digest -> string
15+
#
16+
# Returns the authentication code an a Base64-encoded string.
17+
def base64digest
18+
[digest].pack("m0")
19+
end
20+
1321
class << self
1422
# :call-seq:
1523
# HMAC.digest(digest, key, data) -> aString
@@ -48,6 +56,23 @@ def hexdigest(digest, key, data)
4856
hmac << data
4957
hmac.hexdigest
5058
end
59+
60+
# :call-seq:
61+
# HMAC.base64digest(digest, key, data) -> aString
62+
#
63+
# Returns the authentication code as a Base64-encoded string. The _digest_
64+
# parameter specifies the digest algorithm to use. This may be a String
65+
# representing the algorithm name or an instance of OpenSSL::Digest.
66+
#
67+
# === Example
68+
# key = 'key'
69+
# data = 'The quick brown fox jumps over the lazy dog'
70+
#
71+
# hmac = OpenSSL::HMAC.base64digest('SHA1', key, data)
72+
# #=> "3nybhbi3iqa8ino29wqQcBydtNk="
73+
def base64digest(digest, key, data)
74+
[digest(digest, key, data)].pack("m0")
75+
end
5176
end
5277
end
5378
end

test/openssl/test_hmac.rb

+4
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@ def test_hmac
1010
hmac.update("Hi There")
1111
assert_equal ["9294727a3638bb1c13f48ef8158bfc9d"].pack("H*"), hmac.digest
1212
assert_equal "9294727a3638bb1c13f48ef8158bfc9d", hmac.hexdigest
13+
assert_equal "kpRyejY4uxwT9I74FYv8nQ==", hmac.base64digest
1314

1415
# RFC 4231 4.2. Test Case 1
1516
hmac = OpenSSL::HMAC.new(["0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"].pack("H*"), "SHA224")
1617
hmac.update("Hi There")
1718
assert_equal ["896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22"].pack("H*"), hmac.digest
1819
assert_equal "896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22", hmac.hexdigest
20+
assert_equal "iW+xEoq73xloMhB81J3zP0e0sRaZErpPU2hLIg==", hmac.base64digest
1921
end
2022

2123
def test_dup
@@ -57,6 +59,8 @@ def test_singleton_methods
5759
assert_equal ["9294727a3638bb1c13f48ef8158bfc9d"].pack("H*"), digest
5860
hexdigest = OpenSSL::HMAC.hexdigest("MD5", key, "Hi There")
5961
assert_equal "9294727a3638bb1c13f48ef8158bfc9d", hexdigest
62+
b64digest = OpenSSL::HMAC.base64digest("MD5", key, "Hi There")
63+
assert_equal "kpRyejY4uxwT9I74FYv8nQ==", b64digest
6064
end
6165
end
6266

0 commit comments

Comments
 (0)