Skip to content

Instantly share code, notes, and snippets.

@turlockmike
Last active May 23, 2017 17:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turlockmike/e441a32bf59f6e3c1544 to your computer and use it in GitHub Desktop.
Save turlockmike/e441a32bf59f6e3c1544 to your computer and use it in GitHub Desktop.
AES-256-CBC encryption with 0 byte padding that works with mcrypt
require 'openssl'
class Encryption
attr_accessor :key
IV_SIZE = 16
def initialize(keycode)
md5 = Digest::MD5.new
md5.update(keycode)
self.key = md5.hexdigest[0, IV_SIZE]
end
def encrypt(message)
return nil if message.nil?
iv = SecureRandom.random_bytes(IV_SIZE)
aes = OpenSSL::Cipher.new('AES-128-CBC')
aes.encrypt
aes.padding = 0
aes.key = key
aes.iv = iv
message = iv + message + ("\0" * (16 - (message.length % 16)))
encrypted_data = aes.update(message) + aes.final
CGI.escape(Base64.encode64(encrypted_data).strip)
end
def decrypt(encrypted_data)
return nil if encrypted_data.nil?
encrypted_data = Base64.decode64(encrypted_data)
iv = SecureRandom.random_bytes(IV_SIZE)
aes = OpenSSL::Cipher.new('AES-128-CBC')
aes.decrypt
aes.padding = 0
aes.key = key
aes.iv = iv
message = (aes.update(encrypted_data) + aes.final)
(message[16..-1]).gsub(/\x00/,'')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment