Rijndaelで遊ぶ
急にRubyで暗号化がしたくなりました。
1. cryptをインストールします。
C:\work> gem install crypt Successfully installed crypt-1.1.4
ちなみにファイルは C:\ruby\lib\ruby\gems\1.8\gems\crypt-1.1.4 にインストールされています。
2. スクリプトを作ります。
平文のファイルplain.txtを作り、適当なパスワードで暗号化したファイルencrypt.binを作り、復号(化)したファイル(decrypt.txt)を作ります。
このスクリプトを作るにあたっては、C:\ruby\lib\ruby\gems\1.8\gems\crypt-1.1.4\test\test-rijndael.rbを参照しました。
C:\ruby\lib\ruby\gems\1.8\gems\crypt-1.1.4\crypt\rijndael.rbおよびcbc.rbを読むと、CBCモードが使われ、デフォルトではキーサイズが256ビット、ブロックサイズが128ビットのようです。
require 'crypt/rijndael' PASSWORD = '+UJ7p3vgoXfSyMceANQwyAyIeh/ljJv2' # For example. File.open('plain.txt', 'wb') do |f| f.print <<-'EOD' THE GIFT OF THE MAGI by O. Henry One dollar and eighty-seven cents. That was all. And sixty cents of it was in pennies. Pennies saved one and two at a time by bulldozing the grocer and the vegetable man and the butcher until one's cheeks burned with the silent imputation of parsimony that such close dealing implied. Three times Della counted it. One dollar and eighty- seven cents. And the next day would be Christmas. EOD end crypt = Crypt::Rijndael.new(PASSWORD) crypt.encrypt_file('plain.txt', 'encrypt.bin') crypt.decrypt_file('encrypt.bin', 'decrypt.txt')