Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

個人情報を暗号化して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
tadatti
バックエンドに慣れるためにひたすらwikiる!元フロントエンジニアです
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away