Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save majedbojan/a4318fae42c3943df358b32fc85cab31 to your computer and use it in GitHub Desktop.
Save majedbojan/a4318fae42c3943df358b32fc85cab31 to your computer and use it in GitHub Desktop.
sample encryption and decryption data with Advanced Encryption Standard (AES) for ruby
# Encrypts and Decrypts block of data given an encryption key and an
# initialization vector (iv). Keys, iv's, and the data returned
# are all binary strings. Cipher algorithm should be array [256, CBC],
# or any of the cipher types supported by OpenSSL otherwise default will be used.
# Pass nil if the encryption type doesn't use iv's (like ECB) or ignore it if you using.
# USAGE:
# encrypt_to_hex_format(
# 'ThisPasswordIsReallyHardToGuess', 'initializervector', 'Hey! please encrypt me'
# )
# decrypt_from_hex_format(
# 'ThisPasswordIsReallyHardToGuess', 'initializervector', 'Hey! pass encrypted string here'
# )
require 'openssl'
module Aes
def encrypt_to_hex_format(alg = 'aes-256-cbc', key, iv, data)
bin2hex(send(:perform, :encrypt, alg, key, iv, data))
end
def decrypt_from_hex_format(alg = 'aes-256-cbc', key, iv, data)
perform(:decrypt, alg, key, iv, send(:hex2bin, data))
end
def encrypt_to_base64_format; end # TODO:
def decrypt_from_base64_format; end # TODO:
def perform(method, alg, key, iv, data)
cipher ||= OpenSSL::Cipher.new(alg)
cipher.send(method)
cipher.key = key
cipher.iv = iv unless iv.nil?
cipher.update(data) << cipher.final
end
private
def bin2hex(str)
str.unpack('C*').map { |b| '%02X' % b }.join('')
end
def hex2bin(str)
[str].pack 'H*'
end
def bin2base64; end # TODO:
def base64_bin; end # TODO:
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment