我遇到了rails的问题:我正在尝试为个人使用和学习rails进行密码管理的应用程序,我希望密码加密(现在我使用的是blowfish算法)。我已经安装了crypt gem并编写了一些代码,但是我收到了一个奇怪的错误。
这是我的代码:
app / controller / credentials_controller.rb(脚手架生成)
def create
@credential = current_user.credentials.build(params[:credential])
respond_to do |format|
if @credential.save
format.html { redirect_to(@credential, :notice => 'Credential was successfully created.') }
format.xml { render :xml => @credential, :status => :created, :location => @credential }
else
format.html { render :action => "new" }
format.xml { render :xml => @credential.errors, :status => :unprocessable_entity }
end
end
end
app / models / credential.rb(在db中我创建了一个salt:string列)
require 'crypt/blowfish'
class Credential < ActiveRecord::Base
before_save :hash_password
before_update :hash_password
after_find :unhash_password
private
def hash_password
self.salt = ActiveSupport::SecureRandom.base64(8)
blowfish = Crypt::Blowfish.new(self.salt)
self.pass = blowfish.encrypt_block(self.pass)
end
def unhash_password
end
end
app / views / credential / _form.html.erb
<%= form_for(@credential) do |f| %>
<% if @credential.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@credential.errors.count, "error") %> prohibited this credential from being saved:</h2>
<ul>
<% @credential.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul >
</div>
<% end %>
<div class="field">
<%= f.label :servizio %><br />
<%= f.text_field :servizio %>
</div>
<div class="field">
<%= f.label :url %><br />
<%= f.text_field :url %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :utente %><br />
<%= f.text_field :utente %>
</div>
<div class="field">
<%= f.label :pass %><br />
<%= f.text_field :pass %>
</div>
<div class="field">
<%= f.label :note %><br />
<%= f.text_area :note %>
</div>
<div class="field">
<%= collection_select(:credential, :group_id, current_user.groups, :id, :nome, prompt => 'Seleziona Gruppo') %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
错误是:
`Action Controller: Exception caught
NoMethodError in CredentialsController#create
undefined method '%' for true:TrueClass
app/models/credential.rb:17:in 'hash_password'
app/controllers/credentials_controller.rb:47
app/controllers/credentials_controller.rb:46:in 'create'
注意:如果是凭据模型
def hash_password
self.salt = ActiveSupport::SecureRandom.base64(8)
plainBlock = "ABCD1234"
blowfish = Crypt::Blowfish.new(self.salt)
self.pass = blowfish.encrypt_block(plainBlock)
end
它有效,但密码(显然)始终是ABCD1234。上面的代码,意味着问题是在blowfish.encrypt_block函数中的self.pass。
我做错了什么?
如果我跳过before_save函数,它将作为非加密密码,因此我排除了与路由相关的问题。
非常感谢你! 最好的问候!ps:我正在使用Rails 3.0.8 ps:我正在关注此页http://crypt.rubyforge.org/blowfish.html
答案 0 :(得分:2)
我有解决方案。问题是:
self.salt = ActiveSupport::SecureRandom.base64(8)
在这种情况下,self.salt必须长度为56个字节,因为blowfish需要一个56byte的密钥。
self.pass = blowfish.encrypt_block(self.pass)
在blofwish中,self.pass必须是8个字节长度
最诚挚的问候和感谢您的支持