Extended maintenance of Ruby 1.9.3 ended on February 23, 2015. Read more

In Files

  • digest/lib/digest/hmac.rb

Class/Module Index [+]




An experimental implementation of HMAC keyed-hashing algorithm


CAUTION: Use of this library is discouraged, because this implementation was meant to be experimental but somehow got into the 1.9 series without being noticed. Please use OpenSSL::HMAC in the “openssl” library instead.


require 'digest/hmac'

# one-liner example
puts Digest::HMAC.hexdigest("data", "hash key", Digest::SHA1)

# rather longer one
hmac = Digest::HMAC.new("foo", Digest::RMD160)

buf = ""
while stream.read(16384, buf)

puts hmac.bubblebabble

Public Class Methods

new(key, digester) click to toggle source

Creates a Digest::HMAC instance.

               # File digest/lib/digest/hmac.rb, line 50
def initialize(key, digester)
  @md = digester.new

  block_len = @md.block_length

  if key.bytesize > block_len
    key = @md.digest(key)

  ipad = Array.new(block_len, 0x36)
  opad = Array.new(block_len, 0x5c)

  key.bytes.each_with_index { |c, i|
    ipad[i] ^= c
    opad[i] ^= c

  @key = key.freeze
  @ipad = ipad.pack('C*').freeze
  @opad = opad.pack('C*').freeze

Public Instance Methods

<<(text) click to toggle source
Alias for: update
block_length → Integer click to toggle source

Returns the block length in bytes of the hmac.

               # File digest/lib/digest/hmac.rb, line 118
def block_length
digest_length → Integer click to toggle source

Returns the length in bytes of the hash value of the digest.

               # File digest/lib/digest/hmac.rb, line 110
def digest_length
inspect → string click to toggle source

Creates a printable version of the hmac object.

               # File digest/lib/digest/hmac.rb, line 126
def inspect
  sprintf('#<%s: key=%s, digest=%s>', self.class.name, @key.inspect, @md.inspect.sub(/^\#<(.*)>$/) { $1 });
reset → hmac click to toggle source

Resets the hmac to the initial state and returns self.

               # File digest/lib/digest/hmac.rb, line 92
def reset
update(string) → hmac click to toggle source
hmac << string → hmac

Updates the hmac using a given string and returns self.

               # File digest/lib/digest/hmac.rb, line 82
def update(text)
Also aliased as: <<

Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.

If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.

If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.

If you want to help improve the Ruby documentation, please visit Documenting-ruby.org.

blog comments powered by Disqus