2010/03/11
api documentation | http://mcarpenter.org/rdoc/twofish.rb/index.html |
---|---|
github home | http://github.com/mcarpenter/twofish.rb |
repository URLs |
https://github.com/mcarpenter/twofish.rb.git git://github.com/mcarpenter/twofish.rb.git |
For a small Ruby project I needed Twofish encryption but couldn't find a suitable library. I tried calling Bouncycastle from JRuby (example in the README below). The results were perfectly satisfactory but the process start up time was not, so I translated Guido Flohr's Pure Perl CPAN module to Ruby.
For my small project (reading PasswordSafe vaults
which are generally pretty small) execution speed was not an issue.
YMMV. The latest version of twofish.rb
is compatible with
Ruby 1.8 and 1.9.
This gem implements the Twofish symmetric encryption algorithm in pure Ruby. The original paper describing the cipher “Twofish: A 128-Bit Block Cipher” (Schneier, Kelsey, Whiting, Wagner, Hall, Ferguson) and further information on Twofish can be found at www.schneier.com/twofish.html.
This implementation is derived with kind permission from Guido Flohr’s “pure Perl” module Crypt-Twofish_PP: search.cpan.org/~guido/Crypt-Twofish_PP-0.17. The overall structure and a good number of the comments from that implementation have been retained.
ECB mode:
require 'twofish' key = '1234567890123456' tf = Twofish.new(key, :padding => :zero_byte) ciphertext = tf.encrypt('Lorem ipsum dolor sit amet')
CBC mode with manually specified initialization vector (may alternatively be specified in constructor options hash):
require 'twofish' key = '1234567890123456' tf = Twofish.new(key, :mode => :cbc, :padding => :zero_byte) tf.iv = 'abcdefghijklmnop' ciphertext = tf.encrypt('Lorem ipsum dolor sit amet')
test_twofish.rb defines the unit tests. The iterative test vectors from the original paper are used (although only the final result is checked). The CBC mode test vectors were checked using the BouncyCastle implementation with JRuby as follows:
include Java require 'bcprov-jdk16-145.jar' include_class Java::org.bouncycastle.jce.provider.BouncyCastleProvider include_class Java::org.bouncycastle.crypto.modes.CBCBlockCipher include_class Java::org.bouncycastle.crypto.engines.TwofishEngine include_class Java::org.bouncycastle.crypto.params.KeyParameter include_class Java::org.bouncycastle.crypto.params.ParametersWithIV plaintext = ("