Class: Digest::HMAC

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

Overview

digest/hmac.rb

An experimental implementation of HMAC keyed-hashing algorithm

Overview

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.

Examples

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)
  hmac.update(buf)
end

puts hmac.bubblebabble

Instance Method Summary collapse

Methods inherited from Class

base64digest, bubblebabble, digest, file, hexdigest

Methods included from Instance

#==, #base64digest, #base64digest!, #bubblebabble, #digest, #digest!, #file, #hexdigest, #hexdigest!, #length, #new, #size, #to_s

Constructor Details

#initialize(key, digester) ⇒ HMAC

Creates a Digest::HMAC instance.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File '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)
  end

  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
  @md.update(@ipad)
end

Instance Method Details

#block_lengthObject

call-seq:

hmac.block_length -> Integer

Returns the block length in bytes of the hmac.



118
119
120
# File 'lib/digest/hmac.rb', line 118

def block_length
  @md.block_length
end

#digest_lengthObject

call-seq:

hmac.digest_length -> Integer

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



110
111
112
# File 'lib/digest/hmac.rb', line 110

def digest_length
  @md.digest_length
end

#initialize_copy(other) ⇒ Object

:nodoc:



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

def initialize_copy(other) # :nodoc:
  @md = other.instance_eval { @md.clone }
end

#inspectObject

call-seq:

hmac.inspect -> string

Creates a printable version of the hmac object.



126
127
128
# File 'lib/digest/hmac.rb', line 126

def inspect
  sprintf('#<%s: key=%s, digest=%s>', self.class.name, @key.inspect, @md.inspect.sub(/^\#<(.*)>$/) { $1 });
end

#resetObject

call-seq:

hmac.reset -> hmac

Resets the hmac to the initial state and returns self.



92
93
94
95
96
# File 'lib/digest/hmac.rb', line 92

def reset
  @md.reset
  @md.update(@ipad)
  self
end

#update(text) ⇒ Object Also known as: <<

call-seq:

hmac.update(string) -> hmac
hmac << string -> hmac

Updates the hmac using a given string and returns self.



82
83
84
85
# File 'lib/digest/hmac.rb', line 82

def update(text)
  @md.update(text)
  self
end