class SignedForm::HMAC

Attributes

secret_key[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/signed_form/hmac.rb, line 7
def initialize(options = {})
  self.secret_key = options[:secret_key]

  if secret_key.nil? || secret_key.empty?
    if defined?(::Rails) and ::Rails.application.respond_to?(:secrets)
      self.secret_key = ::Rails.application.secrets.secret_key_base
    end
  end

  if secret_key.nil? || secret_key.empty?
    raise Errors::NoSecretKey, "Please consult the README for instructions on creating a secret key"
  end
end

Public Instance Methods

create(data) click to toggle source
# File lib/signed_form/hmac.rb, line 21
def create(data)
  OpenSSL::HMAC.hexdigest OpenSSL::Digest::SHA1.new, secret_key, data
end
verify(signature, data) click to toggle source
# File lib/signed_form/hmac.rb, line 25
def verify(signature, data)
  secure_compare OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret_key, data), signature
end

Private Instance Methods

secure_compare(a, b) click to toggle source

After the Rack implementation

# File lib/signed_form/hmac.rb, line 32
def secure_compare(a, b)
  return false unless a.bytesize == b.bytesize

  l = a.unpack("C*")

  r, i = 0, -1
  b.each_byte { |v| r |= v ^ l[i+=1] }
  r == 0
end