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 =, :key, :iv)

  def AESCrypt.encrypt(plain_text, opts={})
    cipher =
    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 <<, random_key, random_iv)

  def AESCrypt.decrypt(crypt_struct)
    cipher =
    cipher.key = crypt_struct.key
    cipher.iv = crypt_struct.iv
    cipher.update(crypt_struct.encrypted_data) +
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.

Labels: ,

Comments: Post a Comment

Subscribe to Post Comments [Atom]

<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]