Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.