Last active
May 23, 2017 17:33
-
-
Save turlockmike/e441a32bf59f6e3c1544 to your computer and use it in GitHub Desktop.
AES-256-CBC encryption with 0 byte padding that works with mcrypt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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