class CryptoToolchain::Utilities::HMAC

Attributes

blocksize[R]
hash[R]
key[R]

Public Class Methods

digest(message, key: , hash: CryptoToolchain::Utilities::SHA1) click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 5
def digest(message, key: , hash: CryptoToolchain::Utilities::SHA1)
  new(key: key, hash: hash).digest(message)
end
hexdigest(message, key: , hash: CryptoToolchain::Utilities::SHA1) click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 9
def hexdigest(message, key: , hash: CryptoToolchain::Utilities::SHA1)
  new(key: key, hash: hash).hexdigest(message)
end
new(key: , hash: , blocksize: nil) click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 15
def initialize(key: , hash: , blocksize: nil)
  @key = key
  @hash = hash
  @blocksize = blocksize || determine_blocksize
end

Public Instance Methods

determine_blocksize() click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 29
def determine_blocksize
  case hash.to_s.split(':').last.downcase.gsub(/[^a-z0-9]/i, '')
  when /md(4|5)/
    64
  when /sha(1|224|256)/
    64
  else
    raise ArgumentError.new("Unsupported hash #{hash}")
  end
end
digest(message) click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 21
def digest(message)
  hash.digest(outer_pad + hash.digest(inner_pad + message))
end
hexdigest(message) click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 25
def hexdigest(message)
  digest(message).to_hex
end

Private Instance Methods

blocksize_key() click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 50
def blocksize_key
  @blocksize_key ||= padded(shortened(key))
end
inner_pad() click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 46
def inner_pad
  @inner_pad ||= (0x36.chr * blocksize) ^ blocksize_key
end
outer_pad() click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 42
def outer_pad
  @outer_pad ||= (0x5c.chr * blocksize) ^ blocksize_key
end
padded(input) click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 54
def padded(input)
  if input.bytesize < blocksize
    input.ljust(blocksize, 0.chr)
  else
    input
  end
end
shortened(input) click to toggle source
# File lib/crypto_toolchain/utilities/hmac.rb, line 62
def shortened(input)
  if input.bytesize > blocksize
    hash.digest(input)
  else
    input
  end
end