-
-
Save andrekandore/3140554 to your computer and use it in GitHub Desktop.
AES128, AES256 encrypt/decrypt in Ruby
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" | |
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
I tried to use this and the decryption had problems since it SHA256.digests the key regardless in the decryption, but didn't do the same in the aes256_encrypt call