Skip to content

Instantly share code, notes, and snippets.

@dirtyhenry
Last active June 5, 2018 11:48
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dirtyhenry/4673331 to your computer and use it in GitHub Desktop.
Save dirtyhenry/4673331 to your computer and use it in GitHub Desktop.
Encryption interoperability demo between Ruby and OpenSSL
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}"
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`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment