ばくのエンジニア日誌

技術的なメモなどを書いていきます。

bcrypt-rubyをRailsで使う

パスワードの暗号化に使われるbcrypt-rubyを試してみました。

bcryptとは?

wikipediaより

bcrypt is a key derivation function for passwords designed by Niels Provos and David Mazières, based on the Blowfish cipher, and presented at USENIX in 1999.[1] Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.

要は、汎用的に使えるパスワード暗号化の為の関数のようです。
Rails3のGemfileにはデフォルトでコメントアウトですが記載されているので、まぁこれを使えやってことなんですかね。

gemのインストール

Gemfileでbcrypt-rubyをコメントインします。

# To use ActiveModel has_secure_password
gem 'bcrypt-ruby', '~> 3.0.0'

その後、

bundle

install は省略できるみたいです。

モデル編集

DBにはpassword_digestというカラムを用意しておきます。
一方モデル側には、passwordpassword_digestにアクセスできるようにしておくのと、has_secure_passwordを宣言しておきます。

class User < ActiveRecord::Base
  has_secure_password
  attr_accessible :id, :user_name, :password, :password_digest
end


使ってみる

Viewやコントローラーを作るのは面倒なので、consoleで試してみます。

C:\workspace\railstutorial\bcrypt>rails c

Loading development environment (Rails 3.2.8)
irb(main):001:0> user = User.new(:user_name => 'nobi', :password => 'nobita')
=> #<User id: nil, user_name: "nobi", password_digest: "$2a$10$xkPaCHXr4Rbx3IAPE
iSA/.e8Wm3wlzSziYoRpdKcWh2y...", created_at: nil, updated_at: nil>

:passwordを'nobita'にした部分が、password_digest列で暗号化されているのが分かりますね! この後たとえば

irb(main):002:0> user.authenticate('suneo')
=> false

となりますが、

irb(main):003:0> user.authenticate('nobita')
=> #<User id: nil, user_name: "nobi", password_digest: "$2a$10$xkPaCHXr4Rbx3IAPE
iSA/.e8Wm3wlzSziYoRpdKcWh2y...", created_at: nil, updated_at: nil>

とするときちんと認証されているのがわかります。

参考URL: Ruby on Rails3.2でログイン機能を実装する。