Skip to content

Instantly share code, notes, and snippets.

@saneshark
Created August 24, 2018 06:00
Show Gist options
  • Save saneshark/40472ece3b96df39a19e80defdf10445 to your computer and use it in GitHub Desktop.
Save saneshark/40472ece3b96df39a19e80defdf10445 to your computer and use it in GitHub Desktop.
OpenSSL command-line compatible aes-256-cbc in ruby
require 'openssl'
require 'base64'
require 'pry'
puts 'If you wish to generate a new set of keys and init vectors without salt:'
puts 'openssl enc -nosalt -aes-256-cbc -k <YOUR PASSPHRASE> -P'
puts 'with salt:'
puts 'openssl enc -aes-256-cbc -k <YOUR PASSPHRASE> -P'
puts
# Given a file with the text 'Hello World'
data = File.read("message.txt")
HEX_SECRET = 'C639A572E14D5075C526FDDD43E4ECF6B095EA17783D32EF3D2710AF9F359DD4'
HEX_IV = 'D09A4D2C5DC39843FE075313A7EF2F4C'
# Convert from hex to raw bytes
key = [HEX_SECRET].pack('H*')
iv = [HEX_IV].pack('H*')
# Pad with zero bytes to correct length:
key << ("\x00" * (32 - key.length))
iv << ("\x00" * (16 - iv.length))
# Create an encrypter
cipher = OpenSSL::Cipher::AES.new(256, :CBC)
cipher.encrypt
cipher.key = key
cipher.iv = iv
puts "Hex key: #{key.unpack('H*').first}"
puts "Hex iv: #{iv.unpack('H*').first}"
puts
# Encrypt
encrypted = cipher.update(data) + cipher.final
encrypted = Base64.encode64(encrypted)
puts "Encrypted text: #{encrypted}"
# Create a decrypter
decipher = OpenSSL::Cipher::AES.new(256, :CBC)
decipher.decrypt
decipher.key = key
decipher.iv = iv
# decrypter
encrypted_data = Base64.decode64(encrypted)
plain = decipher.update(encrypted_data) + decipher.final
puts "Decrypted text: #{plain}"
# Ensure a match
puts "Match? #{data == plain}" #=> true
puts
# Verify it is consistent with OpenSSL commandline
puts "openssl command to generate encrypted file: "
puts "openssl enc -nosalt -aes-256-cbc -in message.txt -out message.txt.enc -base64 -K #{key.unpack('H*').first.upcase} -iv #{iv.unpack('H*').first.upcase}"
puts "openssl enc -nosalt -aes-256-cbc -d -in message.txt.enc -base64 -K #{key.unpack('H*').first.upcase} -iv #{iv.unpack('H*').first.upcase}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment