-
-
Save crmaxx/6e245d7b28a0311a350c112444aa0841 to your computer and use it in GitHub Desktop.
AES128, AES256 encrypt/decrypt in Ruby
This file contains hidden or 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" | |
require "digest" | |
def aes128_encrypt(key, data) | |
key = Digest::MD5.digest(key) if(key.kind_of?(String) && 16 != key.bytesize) | |
aes = OpenSSL::Cipher.new('AES-128-CBC') | |
aes.encrypt | |
aes.key = key | |
aes.update(data) + aes.final | |
end | |
def aes256_encrypt(key, data) | |
key = Digest::SHA256.digest(key) if(key.kind_of?(String) && 32 != key.bytesize) | |
aes = OpenSSL::Cipher.new('AES-256-CBC') | |
aes.encrypt | |
aes.key = key | |
aes.update(data) + aes.final | |
end | |
def aes128_decrypt(key, data) | |
key = Digest::MD5.digest(key) if(key.kind_of?(String) && 16 != key.bytesize) | |
aes = OpenSSL::Cipher.new('AES-128-CBC') | |
aes.decrypt | |
aes.key = Digest::MD5.digest(key) | |
aes.update(data) + aes.final | |
end | |
def aes256_decrypt(key, data) | |
key = Digest::SHA256.digest(key) if(key.kind_of?(String) && 32 != key.bytesize) | |
aes = OpenSSL::Cipher.new('AES-256-CBC') | |
aes.decrypt | |
aes.key = Digest::SHA256.digest(key) | |
aes.update(data) + aes.final | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment