Class: HMAC::Base

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

Direct Known Subclasses

SHA1, SHA256, SHA384, SHA512

Instance Method Summary collapse

Constructor Details

#initialize(algorithm, block_size, output_length, key) ⇒ Base

Returns a new instance of Base.



16
17
18
19
20
21
22
23
24
# File 'lib/hmac/hmac.rb', line 16

def initialize(algorithm, block_size, output_length, key)
  @algorithm = algorithm
  @block_size = block_size
  @output_length = output_length
  @status = STATUS_UNDEFINED
  @key_xor_ipad = ""
  @key_xor_opad = ""
  set_key(key) unless key.nil?
end

Instance Method Details

#digestObject



75
76
77
78
# File 'lib/hmac/hmac.rb', line 75

def digest
  check_status
  @md.digest
end

#hexdigestObject



80
81
82
83
# File 'lib/hmac/hmac.rb', line 80

def hexdigest
  check_status
  @md.hexdigest
end

#reset_keyObject



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

def reset_key
  @key_xor_ipad.gsub!(/./, "?")
  @key_xor_opad.gsub!(/./, "?")
  @key_xor_ipad[0..-1] = ""
  @key_xor_opad[0..-1] = ""
  @status = STATUS_UNDEFINED
end

#set_key(key) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/hmac/hmac.rb', line 36

def set_key(key)
  # If key is longer than the block size, apply hash function
  # to key and use the result as a real key.
  key = @algorithm.digest(key) if key.size > @block_size
  key_xor_ipad = "\x36" * @block_size
  key_xor_opad = "\x5C" * @block_size
  for i in 0..key.size - 1
    key_xor_ipad[i] ^= key[i]
    key_xor_opad[i] ^= key[i]
  end
  @key_xor_ipad = key_xor_ipad
  @key_xor_opad = key_xor_opad
  @md = @algorithm.new
  @status = STATUS_INITIALIZED
end

#to_sObject



84
85
86
87
# File 'lib/hmac/hmac.rb', line 84

def hexdigest
  check_status
  @md.hexdigest
end

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



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/hmac/hmac.rb', line 60

def update(text)
  check_status
  # perform inner H
  md = @algorithm.new
  md.update(@key_xor_ipad)
  md.update(text)
  str = md.digest
  # perform outer H
  md = @algorithm.new
  md.update(@key_xor_opad)
  md.update(str)
  @md = md
end