Syntax highlighter

2011-07-31

Cryptographic

暗号技術のこと。
仕事柄よく使うのでSagittariusにもほしいなぁと思い実装中。わざわざJCE使って鍵生成とか、暗号、複合をするのは結構面倒なのでというのが主な動機。
とは言っても中身自体を実装するのは骨が折れるのでlibtomcryptをバンドルしてそのラッパーみたいな感じにしている。
ちなみにこのlibtomcryptがすごくよくできていて、どうしたらこんなきれいな設計できるのかちょっと嫉妬。ドキュメントもすごくしっかりしているという。う~ん、見習わないと。

そんな素敵ライブラリなのだがECBとCBCモードで必要になってくるパディングは自前でやらないといけないということなのでとりあえずPKCS5のパディングを実装することに。理由はJCEのデフォルトだからというだけ。
っでググって見るとあんまり日本語の資料に引っかからない。しょうがないので仕様書の方を確認してみた。
仕様書はここ→RSA Laboratories - PKCS #5: Password-Based Cryptography Standard
おもむろにバージョン2.1のPDFを開いて「Padding」で検索。
3頁の項目4に記述を発見。
4. Concatenate M and a padding string PS to form an encoded message EM:
EM = M || PS ,
where the padding string PS consists of 8-(||M|| mod 8) octets each with value 8-
(||M|| mod 8). The padding string PS will satisfy one of the following statements:
PS = 01 — if ||M|| mod 8 = 7 ;
PS = 02 02 — if ||M|| mod 8 = 6 ;
...
PS = 08 08 08 08 08 08 08 08 — if ||M|| mod 8 = 0.
The length in octets of the encoded message will be a multiple of eight and it will
be possible to recover the message M unambiguously from the encoded message.
(This padding rule is taken from RFC 1423 [3].)
要するに8からデータの長さを8で割った余りを引いてその値を新しいデータに値の数だけ足すということ。
余りが0だった場合は8を8個末尾に追加。

なるほどね。

ちなみに、こんな感じになる予定。
(define key (string->utf8 "8bytekey")) ;; DES requires 8 byte key
(define des-cipher (cipher DES key :mode CBC_MODE :iv (make-bytevector 8) :padder pkcs5-padding)
(encrypt des-cipher (string->utf8 "data to encrypt"))
「:padder」キーワードは手続きを受け取り、パディングとアンパディングを行う。
キーワードを「padder」にしようか「padding」に使用かは悩み中だが、多分「padder」でいいだろう。

No comments:

Post a Comment