我正在使用 rails attr_encrypted gem 在存储到数据库之前对数据进行加密。它在我的应用程序上运行良好,因为它使用提供的密钥加密并通过我的应用程序使用相同的密钥对其进行解密。但是当我使用我的 rails 控制台创建一个实例时,它不会使用应用程序中提供的密钥进行加密(可能每次都使用一些随机密钥),因此当我在我的应用程序中看到该实例时我无法解密它.
下图显示,如果我在控制台中创建了两次同名用户,每次加密的数据都不一样。我正在关注此页面上的教程
当我尝试访问我的应用程序上的页面时,控制台创建的用户显示此错误
这是我的 model.rb 文件的代码,我使用临时密钥进行演示:
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
这是我的控制器代码:
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