Rinjdael (AES) encryption in Ruby

I wrote a blog post regarding the problem in general:

Title: Encryption Compatibility: Matching Encrypted Output on Different Systems
URL: http://blog.chilkatsoft.com/?p=123

To sum it up, these input parameters must match between encryptor and decryptor:
  (1) Algorithm
  (2) Mode (CBC, ECB)
  (3) Key Length (128-bit, 192-bit, 256-bit)
  (4) Initialization Vector
  (5) Secret Key
  (6) Padding Scheme (but only last block will differ if mismatched).

The article discusses each in detail, including character encoding issues if text is involved.
The intent of the article is that anyone can read it regardless of programming language
or encryption package/lib to understand the issues involved. I hope it helps...

-Matt

···

At 09:15 AM 12/5/2006, you wrote:

I've got a quick general question about encryption.

I've encrypted the same string with OpenSSL, ruby-aes, and Crypt, using
the same cipher, key, and IV (I've slightly modified Crypt to accept an
IV) and get different results for all of them.

If all of the variables are the same, why would this be happening?

---- Begin Code Snippit (http://pastie.caboo.se/25895\)

require 'crypt/rijndael'
require 'base64'
require 'ruby-aes/aes'
require 'openssl'

# Modify Crypt::Rijndael lib to accept an IV
module Crypt
  class Rijndael
    def vector() @vector; end

    alias orig_initialize initialize
    def initialize(key, vector, keyBits = 256, blockBits = 128)
      @vector = vector
      orig_initialize(key, keyBits, blockBits)
    end

    alias orig_generate_initialization_vector
generate_initialization_vector
    def generate_initialization_vector( *p )
      @vector || orig_generate_initialization_vector( *p )
    end

    def iv_length() block_size; end

  end
end

  def test_crypt_encryption
    key = '0123456789abcdef0123456789abcdef'
    rijndael = Crypt::Rijndael.new( key, 128, 128 )

    raise Base64.encode64( rijndael.encrypt_string( 'abcdef' ) )
    # returns 'F2wpWlldcZPQlfHOBWZatk8Zq9XNHMRJiB0vC04rZEE='
  end

  def test_openssl_encryption
    key = '0123456789abcdef0123456789abcdef'
    alg = "AES-256-CBC"
    iv = 'abcdefghijklmnop'

    aes = OpenSSL::Cipher::Cipher.new(alg)
    aes.encrypt
    aes.key = key
    aes.iv = iv

    out = aes.update('abcdef')
    out << aes.final
    raise Base64.encode64(out)
    # returns 'jQeE5X55BSwJQav1VV+w1g=='
  end

  def test_aes_encryption
    key = '0123456789abcdef0123456789abcdef'
    iv = 'abcdefghijklmnop'
    raise Base64.encode64( Aes.encrypt_buffer(128, 'CBC', key, iv,
'abcdef') )
    # returns 'fa3taon6wtaPGQ4KgmLrCQ=='
  end

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.1.409 / Virus Database: 268.15.9/571 - Release Date: 12/5/2006

--
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.1.409 / Virus Database: 268.15.9/571 - Release Date: 12/5/2006