public
Last active

Encryption interoperability demo between Ruby and OpenSSL

  • Download Gist
poc-openssl-aes.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
require 'openssl'
require 'base64'
 
# Read the dummy file
data = File.read("test.txt")
 
# Create an encrypter
cipher = OpenSSL::Cipher::AES.new(256, :CBC)
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
puts "Hex key: #{key.unpack('H*')}"
puts "Hex iv: #{iv.unpack('H*')}"
 
# Encrypt and save to a file
encrypted = cipher.update(data) + cipher.final
open "encrypted.txt", "w" do |io| io.write Base64.encode64(encrypted) end
 
# Create a decrypter
decipher = OpenSSL::Cipher::AES.new(256, :CBC)
decipher.decrypt
decipher.key = key
decipher.iv = iv
 
# Decrypt and save to a file
encrypted_data = Base64.decode64(File.read("encrypted.txt"))
plain = decipher.update(encrypted_data) + decipher.final
open "decrypted.txt", "w" do |io| io.write plain end
 
puts data == plain #=> true
 
puts "openssl command: "
puts "openssl aes-256-cbc -d -a -in encrypted.txt -K #{key.unpack('H*').first} -iv #{iv.unpack('H*').first}"
poc-openssl-rsa.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
require 'openssl'
require 'base64'
 
# Generate certificate
# openssl req -x509 -nodes -days 1825 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem
 
# Extract the public key
# openssl rsa -in privkey.pem -pubout > key.pub
 
# Read the dummy file
data = File.read("test.txt")
 
# Create an RSA encrypter
rsa = OpenSSL::PKey::RSA.new File.read('mycert.pem')
 
# Encryption by private key
 
# Encrypt and save to a file
encrypted = rsa.private_encrypt(data)
open "private-encrypted.txt", "w" do |io| io.write Base64.encode64(encrypted) end
 
# Decrypt and save to a file
encrypted_data = Base64.decode64(File.read("private-encrypted.txt"))
plain = rsa.public_decrypt(encrypted_data)
open "private-decrypted.txt", "w" do |io| io.write plain end
 
puts data == plain #=> true
 
# Encryption by public key
 
# Encrypt and save to a file
encrypted = rsa.public_encrypt(data)
open "public-encrypted.txt", "w" do |io| io.write Base64.encode64(encrypted) end
 
# Decrypt and save to a file
encrypted_data = Base64.decode64(File.read("public-encrypted.txt"))
plain = rsa.private_decrypt(encrypted_data)
open "public-decrypted.txt", "w" do |io| io.write plain end
 
puts data == plain #=> true
 
`openssl rsautl -encrypt -pubin -inkey mycert.pub -in test.txt > public-encrypted-cl.txt`
`openssl base64 -e -in public-encrypted-cl.txt -out public-encrypted-cl64.txt`
`openssl base64 -d -in public-encrypted-cl64.txt -out public-decrypted-cl.txt`
puts `openssl rsautl -decrypt -inkey mycert.pem -in public-decrypted-cl.txt`

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.