class Bunq::Encryptor

Constants

AES_ENCRYPTION_METHOD
HMAC_ALGORITHM

Attributes

server_public_key[R]

Public Class Methods

new(server_public_key) click to toggle source
# File lib/bunq/encryptor.rb, line 8
def initialize(server_public_key)
  fail ArgumentError, 'server_public_key is mandatory' unless server_public_key

  @server_public_key = OpenSSL::PKey::RSA.new(server_public_key)
end

Public Instance Methods

encrypt(body) click to toggle source
# File lib/bunq/encryptor.rb, line 14
def encrypt(body)
  headers = {}

  iv, key, encrypted_body = encrypt_body(body)

  headers[Bunq::Header::CLIENT_ENCRYPTION_IV] = Base64.strict_encode64(iv)

  encrypted_key = server_public_key.public_encrypt(key)
  headers[Bunq::Header::CLIENT_ENCRYPTION_KEY] = Base64.strict_encode64(encrypted_key)

  digest = hmac(key, iv + encrypted_body)
  headers[Bunq::Header::CLIENT_ENCRYPTION_HMAC] = Base64.strict_encode64(digest)

  [encrypted_body, headers]
end

Private Instance Methods

encrypt_body(body) click to toggle source
# File lib/bunq/encryptor.rb, line 34
def encrypt_body(body)
  cipher = OpenSSL::Cipher.new(AES_ENCRYPTION_METHOD)
  cipher.encrypt

  iv = cipher.random_iv
  key = cipher.random_key

  encrypted_body = cipher.update(body) + cipher.final

  [iv, key, encrypted_body]
end
hmac(key, content) click to toggle source
# File lib/bunq/encryptor.rb, line 46
def hmac(key, content)
  hmac = OpenSSL::HMAC.new(key, OpenSSL::Digest.new(HMAC_ALGORITHM))
  hmac << content
  hmac.digest
end