In previous post, i’ve described how to create and send encrypted with one time cypher data to server, now its time to receive this data on server side. I will not describe how to setup environment and deploy it some server.

We have encrypted key in request header, and encrypted with this key our ‘very secure data’ in the request body:

x_api = # get header with encrypted key
raw_data = # get raw data from body

api_crypt = APICrypt.new
params = api_crypt.decrypt(x_api, raw_data)

Class APICrypt to deal with this data and key to return decrypted parameters

class APICrypt
  AES_MODE = 'AES-256-ECB'
  AES_KEY_SIZE = 256/8
  def decrypt(x_api, data)
    key = Base64.decode64(x_api)
    aes_key = private_key.private_decrypt(key)
    AESCrypt.decrypt(Base64.decode64(data), aes_key, nil, AES_MODE)
  end

  private

  def private_key
    OpenSSL::PKey::RSA.new(File.read(ENV['API_PRIVATE_KEY']))
  end

end

Helper module to perform AES decryption

require 'openssl'

module AESCrypt

  def AESCrypt.decrypt(encrypted_data, key, iv, cipher_type)
    aes = OpenSSL::Cipher::Cipher.new(cipher_type)
    aes.decrypt
    aes.key = key
    aes.iv = iv if iv != nil
    aes.update(encrypted_data) + aes.final
  end