-
-
Save mbround18/b2b1f6477cafb07fa769cbffa95b7dda to your computer and use it in GitHub Desktop.
AES128 / AES256 CBC with PKCS7Padding 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_cbc_encrypt(key, data, iv) | |
key = Digest::MD5.digest(key) if(key.kind_of?(String) && 16 != key.bytesize) | |
iv = Digest::MD5.digest(iv) if(iv.kind_of?(String) && 16 != iv.bytesize) | |
aes = OpenSSL::Cipher.new('AES-128-CBC') | |
aes.encrypt | |
aes.key = key | |
aes.iv = iv | |
aes.update(data) + aes.final | |
end | |
def aes256_cbc_encrypt(key, data, iv) | |
key = Digest::SHA256.digest(key) if(key.kind_of?(String) && 32 != key.bytesize) | |
iv = Digest::MD5.digest(iv) if(iv.kind_of?(String) && 16 != iv.bytesize) | |
aes = OpenSSL::Cipher.new('AES-256-CBC') | |
aes.encrypt | |
aes.key = key | |
aes.iv = iv | |
aes.update(data) + aes.final | |
end | |
def aes128_cbc_decrypt(key, data, iv) | |
key = Digest::MD5.digest(key) if(key.kind_of?(String) && 16 != key.bytesize) | |
iv = Digest::MD5.digest(iv) if(iv.kind_of?(String) && 16 != iv.bytesize) | |
aes = OpenSSL::Cipher.new('AES-128-CBC') | |
aes.decrypt | |
aes.key = key | |
aes.iv = iv | |
aes.update(data) + aes.final | |
end | |
def aes256_cbc_decrypt(key, data, iv) | |
key = Digest::SHA256.digest(key) if(key.kind_of?(String) && 32 != key.bytesize) | |
iv = Digest::MD5.digest(iv) if(iv.kind_of?(String) && 16 != iv.bytesize) | |
aes = OpenSSL::Cipher.new('AES-256-CBC') | |
aes.decrypt | |
aes.key = key | |
aes.iv = iv | |
aes.update(data) + aes.final | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment