Skip to content

Instantly share code, notes, and snippets.

@nerdinand
Created June 9, 2018 14:04
Show Gist options
  • Save nerdinand/828b23fa5ec200075248b48ed7e10e03 to your computer and use it in GitHub Desktop.
Save nerdinand/828b23fa5ec200075248b48ed7e10e03 to your computer and use it in GitHub Desktop.
AES encryption showcase using OpenSSL in Ruby
require 'openssl'
ALGORITHM = 'AES-256-CBC'
puts 'Enter key to decrypt with (in hexadecimal):'
hex_key = gets.chomp
puts 'Enter message to decrypt (in hexadecimal):'
hex_message = gets.chomp
cipher = OpenSSL::Cipher.new(ALGORITHM)
key = [hex_key].pack('H*')
message = [hex_message].pack('H*')
cipher.decrypt
cipher.key = key
message = cipher.update(message)
message << cipher.final
puts "Decrypted message: #{message}"
require 'openssl'
ALGORITHM = 'AES-256-CBC'
puts 'Enter message to encrypt:'
message = gets.chomp
cipher = OpenSSL::Cipher.new(ALGORITHM)
key = cipher.random_key
hex_key = key.unpack('H*').first
puts "Randomly generated key in hexadecimal: #{hex_key}"
cipher.encrypt
cipher.key = key
encrypted_message = cipher.update(message)
encrypted_message << cipher.final
hex_encrypted_message = encrypted_message.unpack('H*').first
puts "Encrypted message in hexadecimal: #{hex_encrypted_message}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment