Class: Vpago::RsaHandler

Inherits:
Object
  • Object
show all
Defined in:
app/services/vpago/rsa_handler.rb

Instance Method Summary collapse

Constructor Details

#initialize(private_key: nil, public_key: nil) ⇒ RsaHandler



6
7
8
9
# File 'app/services/vpago/rsa_handler.rb', line 6

def initialize(private_key: nil, public_key: nil)
  @private_key = private_key
  @public_key = public_key
end

Instance Method Details

#generate_signature(payload) ⇒ Object



27
28
29
30
31
# File 'app/services/vpago/rsa_handler.rb', line 27

def generate_signature(payload)
  sign_hash = OpenSSL::Digest.new('SHA256')
  private_key = OpenSSL::PKey::RSA.new(@private_key)
  Base64.strict_encode64(private_key.sign(sign_hash, payload))
end

#sign(data) ⇒ Object



11
12
13
14
15
16
17
# File 'app/services/vpago/rsa_handler.rb', line 11

def sign(data)
  raise 'Private key is required to sign data' unless @private_key

  private_key_object = OpenSSL::PKey::RSA.new(@private_key)
  signature = private_key_object.sign(OpenSSL::Digest.new('SHA256'), data)
  "#{data}.#{Base64.strict_encode64(signature)}"
end

#verify(data, signature) ⇒ Object



19
20
21
22
23
24
25
# File 'app/services/vpago/rsa_handler.rb', line 19

def verify(data, signature)
  raise 'Public key is required to verify signature' unless @public_key

  public_key_object = OpenSSL::PKey::RSA.new(@public_key)
  signature_bytes = Base64.decode64(signature)
  public_key_object.verify(OpenSSL::Digest.new('SHA256'), signature_bytes, data)
end