LoginSignup
44

More than 5 years have passed since last update.

railsでdecryptとencryptのsetter、getterを実装する

Last updated at Posted at 2014-08-08

個人情報を暗号化してDBに保存。取り出すときは復号化する。
これをRailsのsetter、getterで実装する方法を紹介します。

ruby
class User < ActiveRecord::Base  
  def encryptor 
    secret = 'hogehofgehogeogeoeogeogoeogeogeogoeogeooge'             
    ::ActiveSupport::MessageEncryptor.new(secret)                
  end

  def email=(val)
    encryptor = self.encryptor 
    write_attribute("email",encryptor.encrypt_and_sign(val))             
  end 

  def email
    encryptor = self.encryptor
    encryptor.decrypt_and_verify(read_attribute("email"))          
  end  
end

これで、saveメソッド実行したり、User.emailのように取り出すときも
復号化、暗号化が実行される。わざわざencrypt_emailのような関数を作らなくてOK

ちなみに、下記のような書き方では実行されない。

ruby
class User < ActiveRecord::Base  
  def encryptor 
    secret = 'nicomakinozoerikotouminikomakikotoumi'
    ::ActiveSupport::MessageEncryptor.new(secret) 
  end

  def email=(val)
    encryptor = self.encryptor
    email = encryptor.encrypt_and_sign(val)                                                                                                                            
  end 

  def email
    encryptor = self.encryptor
    encryptor.decrypt_and_verify(email)
  end  
end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44