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.



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

def initialize(secret, algorithm: 'sha512')
  @secret = T.let(secret, String)
  @algorithm = T.let(algorithm, String)
  # Fail fast on an unsupported algorithm (OpenSSL's error class varies).
  OpenSSL::HMAC.hexdigest(@algorithm, @secret, '')
rescue StandardError => e
  raise Error,
        "Unsupported HMAC algorithm #{algorithm.inspect}: #{e.message}"
end

Instance Attribute Details

#algorithmObject (readonly)

Returns the value of attribute algorithm.



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

def algorithm
  @algorithm
end

Instance Method Details

#inspectObject



24
25
26
# File 'lib/m2m_keygen/signature.rb', line 24

def inspect
  "#<#{self.class.name} algorithm=#{@algorithm.inspect}>"
end

#sign(verb:, path:, expiry:, nonce:, query: '', body: '') ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/m2m_keygen/signature.rb', line 38

def sign(verb:, path:, expiry:, nonce:, query: '', body: '')
  OpenSSL::HMAC.hexdigest(
    @algorithm,
    @secret,
    Canonicalizer.canonical(
      verb: verb,
      path: path,
      expiry: expiry,
      nonce: nonce,
      query: query,
      body: body,
    ),
  )
end

#validate(signature:, verb:, path:, expiry:, nonce:, query: '', body: '') ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/m2m_keygen/signature.rb', line 64

def validate(signature:, verb:, path:, expiry:, nonce:, query: '', body: '')
  OpenSSL.fixed_length_secure_compare(
    sign(
      verb: verb,
      path: path,
      expiry: expiry,
      nonce: nonce,
      query: query,
      body: body,
    ),
    signature,
  )
rescue StandardError
  false
end