Skip to content

Instantly share code, notes, and snippets.

@RiANOl
Last active April 13, 2024 06:17
Show Gist options
  • Star 52 You must be signed in to star a gist
  • Fork 19 You must be signed in to fork a gist
  • 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
@efreesen
Copy link

efreesen commented Feb 1, 2013

Hey in line 24 and 32 you are doing the digest again.

And thank you for the code ;)

@xxxazxxx
Copy link

@efreesen is right. there is problem on line 24 and 32.

it should be
aes.key = key

@fooledbyprimes
Copy link

Nice. If I want to encrypt using openssl command line and then decrypt in Ruby then I always get things messed up in the Ruby decypt code. I think it would be helpful to have the command line analogs for comparison for newbies.

@JasonBristol
Copy link

Thank you, this is helpful

@RiANOl
Copy link
Author

RiANOl commented Feb 4, 2014

Thanks, fixed

@awesome
Copy link

awesome commented Feb 8, 2014

awesome!

@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