Class: HMAC::Generator

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

Instance Method Summary collapse

Constructor Details

#initialize(context:, public: false, secret: nil) ⇒ Generator

Returns a new instance of Generator.

Raises:



3
4
5
6
7
8
9
10
# File 'lib/hmac/generator.rb', line 3

def initialize(context:, public: false, secret: nil)
  @context = context
  @public = public
  @digest = OpenSSL::Digest.new("SHA256")
  @hmac_key = secret || HMAC.configuration.secret

  raise ConfigurationError, "HMAC secret is not configured" if @hmac_key.nil?
end

Instance Method Details

#generate(id:, extra_fields: {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/hmac/generator.rb', line 12

def generate(id:, extra_fields: {})
  OpenSSL::HMAC.new(hmac_key, digest).tap do |hmac|
    hmac.update(id.to_s)
    hmac.update(context.to_s)
    hmac.update("public") if public?
    extra_fields.sort.each do |_, value|
      hmac.update(value.to_s)
    end
  end.hexdigest
end