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

Use constant time compare in HMAC example #284

Merged
merged 2 commits into from
Nov 3, 2019
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
14 changes: 4 additions & 10 deletions ext/openssl/ossl_hmac.c
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,12 @@ ossl_hmac_alloc(VALUE klass)
*
* === A note about comparisons
*
* Two instances won't be equal when they're compared, even if they have the
* same value. Use #to_s or #hexdigest to return the authentication code that
* the instance represents. For example:
* Two instances can be securely compared with #== in constant time:
*
* other_instance = OpenSSL::HMAC.new('key', OpenSSL::Digest.new('sha1'))
* #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
* instance
* #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
* instance == other_instance
* #=> false
* instance.to_s == other_instance.to_s
* #=> true
* #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
* instance == other_instance
* #=> true
*
*/
static VALUE
Expand Down
1 change: 1 addition & 0 deletions lib/openssl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
require_relative 'openssl/cipher'
require_relative 'openssl/config'
require_relative 'openssl/digest'
require_relative 'openssl/hmac'
require_relative 'openssl/x509'
require_relative 'openssl/ssl'
require_relative 'openssl/pkcs5'
Expand Down
13 changes: 13 additions & 0 deletions lib/openssl/hmac.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# frozen_string_literal: true

module OpenSSL
class HMAC
# Securely compare with another HMAC instance in constant time.
def ==(other)
return false unless HMAC === other
return false unless self.digest.bytesize == other.digest.bytesize

OpenSSL.fixed_length_secure_compare(self.digest, other.digest)
end
end
end
10 changes: 10 additions & 0 deletions test/test_hmac.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ def test_reset_keep_key
second = h1.update("test").hexdigest
assert_equal first, second
end

def test_eq
h1 = OpenSSL::HMAC.new("KEY", "MD5")
h2 = OpenSSL::HMAC.new("KEY", OpenSSL::Digest.new("MD5"))
h3 = OpenSSL::HMAC.new("FOO", "MD5")

assert_equal h1, h2
refute_equal h1, h2.digest
refute_equal h1, h3
end
end

end