I am using rails attr_encrypted gem for encrypting data before storing in database. It works fine on my application as it encrypts with the provided key and decrypts it using the same key via my application. But when I create a instance with my rails console, it does not encrypt with the key that is provided in the application ( uses some random key each time maybe) and hence I am not able to decrypt it when I see that instance in my application.
Below picture shows that if I create the user with the same name twice in console, each time the encrypted data is different. I am following the tutorial on this page
When I try to access the page on my application, the user made by console are showing this error
Here is my code for my model.rb file and am using a temporary key for demo purpose:
class Model < ActiveRecord::Base
attr_encrypted_options.merge!(:encode => true)
attr_encrypted :user, key: "aMI9uV87sL46Nwv+8qeAOUp5nsvzp5C/FkVAOFkcCtk="
attr_encrypted :password, key: "aMI9uV87sL46Nwv+8qeAOUp5nsvzp5C/FkVAOFkcCtk="
end
Here is my controller code:
class ModelsController < ApplicationController
before_action :set_model, only: [:show, :edit, :update, :destroy]
# GET /models
# GET /models.json
def index
@models = Model.all
end
# GET /models/1
# GET /models/1.json
def show
end
# GET /models/new
def new
@model = Model.new
end
# GET /models/1/edit
def edit
end
# POST /models
# POST /models.json
def create
@model = Model.new(model_params)
respond_to do |format|
if @model.save
format.html { redirect_to @model, notice: 'Model was successfully created.' }
format.json { render :show, status: :created, location: @model }
else
format.html { render :new }
format.json { render json: @model.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /models/1
# PATCH/PUT /models/1.json
def update
respond_to do |format|
if @model.update(model_params)
format.html { redirect_to @model, notice: 'Model was successfully updated.' }
format.json { render :show, status: :ok, location: @model }
else
format.html { render :edit }
format.json { render json: @model.errors, status: :unprocessable_entity }
end
end
end
# DELETE /models/1
# DELETE /models/1.json
def destroy
@model.destroy
respond_to do |format|
format.html { redirect_to models_url, notice: 'Model was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_model
@model = Model.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def model_params
params.require(:model).permit(:user, :password, :host)
end
end