Class: M2mKeygen::Signature

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/m2m_keygen/signature.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret, algorithm: 'sha512') ⇒ Signature

Returns a new instance of Signature.



17
18
19
20
21
# File 'lib/m2m_keygen/signature.rb', line 17

def initialize(secret, algorithm: 'sha512')
  @secret = T.let(secret, String)
  @algorithm = T.let(algorithm, String)
  OpenSSL::HMAC.hexdigest(@algorithm, @secret, '')
end

Instance Attribute Details

#algorithmObject (readonly)

Returns the value of attribute algorithm.



14
15
16
# File 'lib/m2m_keygen/signature.rb', line 14

def algorithm
  @algorithm
end

#secretObject (readonly)

Returns the value of attribute secret.



11
12
13
# File 'lib/m2m_keygen/signature.rb', line 11

def secret
  @secret
end

Instance Method Details

#sign(params:, verb:, path:) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/m2m_keygen/signature.rb', line 30

def sign(params:, verb:, path:)
  OpenSSL::HMAC.hexdigest(
    @algorithm,
    @secret,
    "#{verb.to_s.upcase}#{path}#{ParamsEncoder.new(params).encode}",
  )
end

#validate(params:, verb:, path:, signature:) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/m2m_keygen/signature.rb', line 46

def validate(params:, verb:, path:, signature:)
  if OpenSSL.methods.include?(:fixed_length_secure_compare)
    OpenSSL.fixed_length_secure_compare(
      sign(params: params, verb: verb, path: path),
      signature,
    )
  else
    fallback_fixed_length_secure_compare(
      sign(params: params, verb: verb, path: path),
      signature,
    )
  end
rescue StandardError
  false
end