Created
December 4, 2010 20:24
-
-
Save erik-megarad/728456 to your computer and use it in GitHub Desktop.
AES Encryption for Ruby 1.9
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' | |
module AESCrypt | |
# Decrypts a block of data (encrypted_data) given an encryption key | |
# and an initialization vector (iv). Keys, iv's, and the data | |
# returned are all binary strings. Cipher_type should be | |
# "AES-256-CBC", "AES-256-ECB", or any of the cipher types | |
# supported by OpenSSL. Pass nil for the iv if the encryption type | |
# doesn't use iv's (like ECB). | |
#:return: => String | |
#:arg: encrypted_data => String | |
#:arg: key => String | |
#:arg: iv => String | |
#:arg: cipher_type => String | |
def AESCrypt.decrypt(encrypted_data, key, iv, cipher_type) | |
aes = OpenSSL::Cipher::Cipher.new(cipher_type) | |
aes.decrypt | |
aes.key = key | |
aes.iv = iv if iv != nil | |
aes.update([encrypted_data].pack("H*")) + aes.final | |
end | |
# Encrypts a block of data given an encryption key and an | |
# initialization vector (iv). Keys, iv's, and the data returned | |
# are all binary strings. Cipher_type should be "AES-256-CBC", | |
# "AES-256-ECB", or any of the cipher types supported by OpenSSL. | |
# Pass nil for the iv if the encryption type doesn't use iv's (like | |
# ECB). | |
#:return: => String | |
#:arg: data => String | |
#:arg: key => String | |
#:arg: iv => String | |
#:arg: cipher_type => String | |
def AESCrypt.encrypt(data, key, iv, cipher_type) | |
aes = OpenSSL::Cipher::Cipher.new(cipher_type) | |
aes.encrypt | |
aes.key = key | |
aes.iv = iv if iv != nil | |
(aes.update(data) + aes.final).unpack("H*")[0] | |
end | |
end | |
# And use thusly: | |
AESCrypt.encrypt(string, "mykey", nil, "AES-256-CBC") | |
AESCrypt.decrypt(string, "mykey", nil, "AES-256-CBC") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, works great! Any tips for generating keys? Is a long 'random' string sufficient?