Crypt::CBC による Blowfish 暗号化

This module is a Perl-only implementation of the cryptographic cipher block chaining mode (CBC). In combination with a block cipher such as DES or IDEA, you can encrypt and decrypt messages of arbitrarily long length. The encrypted messages are compatible with the encryption format used by SSLeay, and can be made compatible with the newer OpenSSL package by specifying the -salt argument.

先の XML.com の記事で Blowfish アルゴリズムによる暗号化という話が出てきます。で、その中でC言語による実装の具体的なコードも出てきます。

では、Blowfish を Perl で利用するにはどうしたらいいか、ということになるのですがそこはやはり CPAN の力を借りるのが手っ取り早い。Crypt::Blowfish を使うのが一つの手で、さらに一歩進めてブロック暗号の一つである CBC (Cipher Block Chaining) により暗号化を行う Crypt::CBC を使うと良いようです。随分前にちょっとだけ調べたときのメモが出てきたので、覚書代わりにエントリーしておきます。

Crypt::CBC で Blowfish 暗号化を行うには、

#!/usr/local/bin/perl
use strict;
use Crypt::CBC;
  
my $strings = "ほげほげほげ"
my $cbc = Crypt::CBC->new({
    key => 'naoya',
    cipher => 'Blowfish',
    padding =>'null'
});
my $crypted = $cbc->encrypt_hex($strings);

print $crypted, "\n";

とこんなコードになります。コンストラクタの cipher で CBC で使える暗号アルゴリズムを選択する。Crypt::FooBar になっているモジュールであればここに指定可能のようです。Blowfish で Crypt::Blowfish が内部で利用されます。Blowfish_PP にすると Crypt::Blowfish_PP という Pure Perl な Blowfish 実装が使われます。key には復号化に必要になる秘密鍵を指定します。

逆に復号化するときは、

#!/usr/local/bin/perl
use strict;
use Crypt::CBC;
  
my $strings = '(暗号化した文字列)'
my $cbc = Crypt::CBC->new({
    key => 'naoya',
    cipher => 'Blowfish',
    padding => 'null'
});
my $decrypted = $cbc->decrypt_hex($strings);
  
print $decrypted, "\n";

となります。中の実装を詳しく知らなくても、その恩恵を得ることができるのがお分かりかと思います。

ブロック暗号やCBC、より詳しい Crypt::CBC の使い方なんかは Cepheidさんのところにあるドキュメントが参考になります。

暗号化関連はさすがに難しいです。