Class: OpenSSL::HMAC

Inherits:
Object
  • Object
show all
Defined in:
lib/openssl/hmac.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.base64digest(digest, key, data) ⇒ Object

: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="


73
74
75
# File 'lib/openssl/hmac.rb', line 73

def base64digest(digest, key, data)
  [digest(digest, key, data)].pack("m0")
end

Instance Method Details

#==(other) ⇒ Object

Securely compare with another HMAC instance in constant time.



6
7
8
9
10
11
# File 'lib/openssl/hmac.rb', line 6

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

#base64digestObject

:call-seq:

hmac.base64digest -> string

Returns the authentication code an a Base64-encoded string.



17
18
19
# File 'lib/openssl/hmac.rb', line 17

def base64digest
  [digest].pack("m0")
end

#digest(digest, key, data) ⇒ Object

:call-seq:

HMAC.digest(digest, key, data) -> aString

Returns the authentication code as a binary 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.digest('SHA1', key, data)
#=> "\xDE|\x9B\x85\xB8\xB7\x8A\xA6\xBC\x8Az6\xF7\n\x90p\x1C\x9D\xB4\xD9"


35
36
37
38
39
# File 'lib/openssl/hmac.rb', line 35

def digest(digest, key, data)
 hmac = new(key, digest)
 hmac << data
 hmac.digest
end

#hexdigest(digest, key, data) ⇒ Object

:call-seq:

HMAC.hexdigest(digest, key, data) -> aString

Returns the authentication code as a hex-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.hexdigest('SHA1', key, data)
#=> "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"


54
55
56
57
58
# File 'lib/openssl/hmac.rb', line 54

def hexdigest(digest, key, data)
 hmac = new(key, digest)
 hmac << data
 hmac.hexdigest
end