Skip to content

Instantly share code, notes, and snippets.

@bpietraga
Created August 20, 2017 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bpietraga/684ccf142b763870071a1d09bf380d63 to your computer and use it in GitHub Desktop.
Save bpietraga/684ccf142b763870071a1d09bf380d63 to your computer and use it in GitHub Desktop.
require 'base64'
require 'net/http'
require 'uri'
require 'openssl'
require 'json'
class MessageExchange
def initialize(url)
@uri = URI(url)
@cipher_key = 'this_key_have_to_equal_32_bytes!'
@cipher_iv = '2840234823308290'
end
def call
puts decrypted_message
end
private
def decrypted_message
message = JSON.parse(api_response.body)
decrypt(message['data'])
end
def api_response
http_client.request(request_content)
rescue
raise 'Calling server failed'
end
def http_client
Net::HTTP.new(@uri.host, @uri.port)
end
def request_content
req = Net::HTTP::Post.new(@uri.path, 'Content-Type' => 'application/json')
req.body = json_message
req
end
def json_message
{ 'data' => encrypted_content }.to_json
end
def encrypted_content
encrypt(message_content)
end
def message_content
{ 'name' => 'Arnold',
'surname' => 'Schwarzeneger' }.to_json
end
def encrypt(data)
cipher = OpenSSL::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.key = @cipher_key
cipher.iv = @cipher_iv
encrypted = cipher.update(data) + cipher.final
Base64.strict_encode64(encrypted)
end
def decrypt(cipher_text)
data = Base64.strict_decode64(cipher_text)
decipher = OpenSSL::Cipher.new('aes-256-cbc')
decipher.decrypt
decipher.key = @cipher_key
decipher.iv = @cipher_iv
base64_string = decipher.update(data) + decipher.final
end
end
MessageExchange.new('http://localhost:4000/api/encrypted').call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment