Last active
April 13, 2024 06:17
-
-
Save RiANOl/1077760 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 |
thanks, it works in ruby 2.4 on windows 10!
How to go for PKCS5 encrypting in Ruby? I can't find any information on this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you decrypt these in java?