Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hmac: implement base64digest methods #381

Merged
merged 1 commit into from
Jul 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions lib/openssl/hmac.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ def ==(other)
OpenSSL.fixed_length_secure_compare(self.digest, other.digest)
end

# :call-seq:
# hmac.base64digest -> string
#
# Returns the authentication code an a Base64-encoded string.
def base64digest
[digest].pack("m0")
end

class << self
# :call-seq:
# HMAC.digest(digest, key, data) -> aString
Expand Down Expand Up @@ -48,6 +56,23 @@ def hexdigest(digest, key, data)
hmac << data
hmac.hexdigest
end

# :call-seq:
# HMAC.base64digest(digest, key, data) -> aString
#
# Returns the authentication code as a Base64-encoded string. The _digest_
# parameter specifies the digest algorithm to use. This may be a String
# representing the algorithm name or an instance of OpenSSL::Digest.
#
# === Example
# key = 'key'
# data = 'The quick brown fox jumps over the lazy dog'
#
# hmac = OpenSSL::HMAC.base64digest('SHA1', key, data)
# #=> "3nybhbi3iqa8ino29wqQcBydtNk="
def base64digest(digest, key, data)
[digest(digest, key, data)].pack("m0")
end
end
end
end
4 changes: 4 additions & 0 deletions test/openssl/test_hmac.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ def test_hmac
hmac.update("Hi There")
assert_equal ["9294727a3638bb1c13f48ef8158bfc9d"].pack("H*"), hmac.digest
assert_equal "9294727a3638bb1c13f48ef8158bfc9d", hmac.hexdigest
assert_equal "kpRyejY4uxwT9I74FYv8nQ==", hmac.base64digest

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

def test_dup
Expand Down Expand Up @@ -57,6 +59,8 @@ def test_singleton_methods
assert_equal ["9294727a3638bb1c13f48ef8158bfc9d"].pack("H*"), digest
hexdigest = OpenSSL::HMAC.hexdigest("MD5", key, "Hi There")
assert_equal "9294727a3638bb1c13f48ef8158bfc9d", hexdigest
b64digest = OpenSSL::HMAC.base64digest("MD5", key, "Hi There")
assert_equal "kpRyejY4uxwT9I74FYv8nQ==", b64digest
end
end

Expand Down