Skip to content

Instantly share code, notes, and snippets.

@RiANOl
Last active April 13, 2024 06:17
Show Gist options
  • Save RiANOl/1077760 to your computer and use it in GitHub Desktop.
Save RiANOl/1077760 to your computer and use it in GitHub Desktop.
AES128 / AES256 CBC with PKCS7Padding in Ruby
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
@nurettin
Copy link

nurettin commented Jan 7, 2017

How do you decrypt these in java?

@edgardo001
Copy link

thanks, it works in ruby ​​2.4 on windows 10!

@arslanaly47
Copy link

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