Skip to content

Instantly share code, notes, and snippets.

@andrekandore
Forked from RiANOl/gist:1077760
Created July 19, 2012 03:27
Show Gist options
  • Save andrekandore/3140554 to your computer and use it in GitHub Desktop.
Save andrekandore/3140554 to your computer and use it in GitHub Desktop.
AES128, AES256 encrypt/decrypt in Ruby
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
@veverkap
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment