Node.jsでbcrypt

 expressでユーザ認証を試そうとexamplesのauthを眺めていたら、そこではパスワードの暗号化にcryptを使っていて、でもコメントではbcrypt使ったほうがよいよ!的なことが書かれていたので調べてみました。
https://github.com/visionmedia/express/blob/master/examples/auth/app.js
https://github.com/ncb000gt/node.bcrypt.js
http://en.wikipedia.org/wiki/Crypt_(Unix)#Blowfish-based_scheme
http://codahale.com/how-to-safely-store-a-password/
(ちゃんと読んでませんが…)
まあ、使ってみるのがいちばんということで、

npm install bcrypt

npmなら簡単インストール。
bcryptSample.js

var bcrypt = require('bcrypt');
var salt = bcrypt.gen_salt_sync(10);
var hash = bcrypt.encrypt_sync('chaimaxx', salt);
console.log('salt -> ' + salt);
console.log('hash -> ' + hash);
var result = bcrypt.compare_sync('chaimaxx', hash);
console.log('hash=="chaimaxx" -> ' + result);
var result = bcrypt.compare_sync('chaimangana', hash);
console.log('hash=="chaimangana" -> ' + result);
$ node bcryptSample.js
salt -> $2a$10$twmbksH.g9pPlakoOtTBNO
hash -> $2a$10$twmbksH.g9pPlakoOtTBNO4hW6wOaF8rkxU0lku/jyhF3d6GgzFCK
hash=="chaimaxx" -> true
hash=="chaimangana" -> false

こんな感じになります。saltがhashに含まれているので保存するのはhashだけでいいんです! 簡単ですね。