Monday, July 20, 2009
AES Encryption Wrapper for Ruby
I thought I would share my AES encryption wrapper for Ruby. The attached code utilizes openssl.
require 'openssl' module AESCrypt DEFAULT_CIPHER_TYPE = 'aes-256-cbc' CRYPT_STRUCT = Struct.new(:encrypted_data, :key, :iv) def AESCrypt.encrypt(plain_text, opts={}) cipher = OpenSSL::Cipher::Cipher.new(DEFAULT_CIPHER_TYPE) cipher.encrypt opts.reverse_merge! :key => cipher.random_key, :iv => cipher.random_iv cipher.key = random_key = opts[:key] cipher.iv = random_iv = opts[:iv] encrypted_data = cipher.update(plain_text) encrypted_data << cipher.final CRYPT_STRUCT.new(encrypted_data, random_key, random_iv) end def AESCrypt.decrypt(crypt_struct) cipher = OpenSSL::Cipher::Cipher.new(DEFAULT_CIPHER_TYPE) cipher.decrypt cipher.key = crypt_struct.key cipher.iv = crypt_struct.iv cipher.update(crypt_struct.encrypted_data) + cipher.final end end
This code is pretty straightforward. One thing of interest is that we are using a random AES key and initialization vector on lines 10 and 11 respectively. This results in consumers of this API needing to store the key and initialization vector in order to decrypt, which is why a CRYPT_STRUCT is returned on line 14.
The source and test files are available at the my_password_manager github site.
Subscribe to Posts [Atom]