LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】ActiveRecordのデータを暗号化しよう

Last updated at Posted at 2021-07-31

active_record_encryptionというgemを使う

誰でも簡単3ステップで導入

①gemを導入

Gemfileに以下を追記

gem 'active_record_encryption'
bundle install

②カラムを設定

blob型でカラムを設定します。例えばユーザーの本名、生年月日を暗号化するならこんな感じ

class DeviseCreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string     :email,              null: false, default: ""
      t.string     :encrypted_password, null: false, default: ""
      t.string     :uid,                null: false
      t.string     :nickname,           null: false
      t.blob     :first_name,         null: false
      t.blob     :last_name,          null: false
      t.blob     :first_name_kana,    null: false
      t.blob     :last_name_kana,     null: false
      t.blob       :birth_date,         null: false
      t.references :organization,       foreign_key: true

③モデルに暗号化したカラムの元データを定義

モデルに以下のように記載します。

encrypted_attribute(:first_name, :string, default: "")
encrypted_attribute(:last_name, :string, default: "")
encrypted_attribute(:first_name_kana, :string, default: "")
encrypted_attribute(:last_name_kana, :string, default: "")
encrypted_attribute(:birth_date, :date)

④暗号化方式を定義

config/initializers/active_record_encryption.rbに以下のように記述します。
暗号化key、saltについては知られちゃまずいので環境変数で設定します。

ActiveRecordEncryption.default_encryption = {
  encryptor: :active_support,
  key: ENV['ENCRYPTION_KEY'],
  salt: ENV['ENCRYPTION_SALT']
}

⑤DBにデータを保存する

この状態でDBにデータを保存するとこんな感じの値が入ります。
_MySQL_5_6_50__localhost_media_app_development_users.png

見た目はなんのこっちゃわからないのですが、値を取り出すとちゃんと保存時に指定した値が取り出せます。

[2] pry(main)> user.first_name
=> "山田"

感想

結構簡単に実装できてしまうのでセキュリティ的にどうなの?って感じもする。
SQLインジェクションとかで値を抜き取られたときとかに強そう

0
0
0

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
0
0