must specify an iv attr_encrypted, how to check login and password

1.4k Views Asked by At

Hi have the following model:

class User < ActiveRecord::Base

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

Where I added the 4 cols to my model

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

Now I want to check if email and password are correct, but I don't know how to process:

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

but when I do:

email = User.encrypt_email("[email protected]", key: secret_key_data)

I got this error:

ArgumentError: must specify an iv

Question is, where do I get the iv from, and how do I encrypt to be able to test in the db if the login is right?

Thanks a lot!

1

There are 1 best solutions below

0
On

Some older versions of attr_encrypted have quirky (or no) initial vector (iv) handling. Be aware of the version of attr_encrypted that you are using. I think this is your problem. Try attr_encrypted v3.1.0 with Rails v4.1.16.

In your migration:

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 

In your model:

class User < ActiveRecord::Base

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

In your controller:

  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

This version/configuration works for me.