Class: CoderDecorator::Coders::HMAC

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

Overview

Actuall, it doesn’t encode, instead, it appends a hex HMAC to the input data in this format:

"#{data}--#{hmac}"

Defined Under Namespace

Classes: InvalidSignature

Constant Summary collapse

REGEXP =
/\A(.*)--(.*)\z/

Instance Attribute Summary

Attributes inherited from Coder

#coder

Instance Method Summary collapse

Constructor Details

#initialize(coder = nil, secret:, old_secret: nil, digest: 'SHA1') ⇒ HMAC

Returns a new instance of HMAC.



18
19
20
21
22
23
# File 'lib/coder_decorator/coders/hmac.rb', line 18

def initialize(coder = nil, secret:, old_secret: nil, digest: 'SHA1')
  super(coder)
  @secret = secret
  @old_secret = old_secret
  @digest = ::OpenSSL::Digest.new(digest)
end

Instance Method Details

#decode(str) ⇒ Object

Raises:



31
32
33
34
35
36
37
# File 'lib/coder_decorator/coders/hmac.rb', line 31

def decode(str)
  match_data = REGEXP.match(str)
  data, hmac = match_data.captures if match_data
  secrets = [@secret, @old_secret]
  raise InvalidSignature unless data && hmac && secrets.any? { |secret| secure_compare(hmac, generate_hmac(secret, data)) }
  coder.decode(data)
end

#encode(str) ⇒ Object



25
26
27
28
29
# File 'lib/coder_decorator/coders/hmac.rb', line 25

def encode(str)
  data = coder.encode(str)
  hmac = generate_hmac(@secret, data)
  "#{data}--#{hmac}"
end