必须指定一个iv attr_encrypted,如何检查登录名和密码

时间:2018-08-04 09:11:48

标签: ruby-on-rails ruby ruby-on-rails-5 attr-encrypted

嗨,他的模型如下:

class User < ActiveRecord::Base

     secret_key = ENV['DB_COL_ENCRYPTED_KEY']
     attr_encrypted :email, :key => secret_key
     attr_encrypted :password, :key => secret_key
     [...]
end

我在模型中添加了4个列

rails g migration AddEncryptedColumnsToUser encrypted_email:string encrypted_password:string encrypted_email_iv:string encrypted_password_iv:string 

现在我要检查电子邮件和密码是否正确,但是我不知道如何处理:

secret_key_data = "my big secret 32 bits key "
email = User.encrypt_email("test@test.com", key: secret_key_data)
password = User.encrypt_password("test", key: secret_key_data)
User.where('(encrypted_email) LIKE ? AND (encrypted_password) LIKE ? ', email,password)

但是当我这样做时:

email = User.encrypt_email("test@test.com", key: secret_key_data)

我收到此错误:

ArgumentError: must specify an iv

问题是,我从哪里获得静脉注射,如果登录正确,我该如何加密才能在数据库中进行测试?

非常感谢!

1 个答案:

答案 0 :(得分:0)

attr_encrypted的某些旧版本具有古怪的(或没有)初始向量(iv)处理。请注意您正在使用的attr_encrypted的版本。我认为这是您的问题。在Rails v4.1.16中尝试 attr_encrypted v3.1.0

在您的迁移中:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :username, null: false
      t.string :encrypted_email
      t.string :encrypted_email_iv
      t.string :encrypted_password
      t.string :encrypted_password_iv
      t.timestamps
    end
  end
end 

在您的模型中:

class User < ActiveRecord::Base

  attr_encrypted :email, :password, 
                 key: 'Some 256-bit key here'
end

在您的控制器中:

  private

    # Never trust parameters from the scary internet, only allow the white list through.
    def server_params
      params.require(:server).permit(:username, :email, :password)
    end

此版本/配置对我有效。