设计:手动加密密码并直接存储 [英] Devise: manually encrypt password and store directly

查看:82
本文介绍了设计:手动加密密码并直接存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从旧数据库迁移大量用户。为此,我使用activerecord-import并尝试将所有用户数据直接保存到数据库(绕过用户模型)。

I'm trying to migrate a ton of users from an old database. To do this, I'm using activerecord-import and trying to save all my user data directly to DB (bypassing the User model).

我的问题:我需要获取旧用户的纯文本密码,对其进行加密,然后直接存储到数据库。我知道如何使用Devise 生成密码,但是我想知道是否有一种方法可以获取哈希密码,然后将密码直接存储到数据库中。

My issue: I need to take the old user's plain-text password, encrypt it, and store directly to the DB. I know how to generate a password using Devise, but am wondering if there's a way to get a hashed password that I can store directly to the database.

希望这样做:

new_hashed_password = Devise.awesome_encrypting_method(old_user.password)

然后将 new_hashed_pa​​ssword直接存储到数据库中,而无需通过模型。我在Devise中进行了挖掘,发现了以下内容:

Then store "new_hashed_password" directly into the DB without going through the model. I dug around in Devise and found this:

def password_digest(password)
  ::BCrypt::Password.create("#{password}#{self.class.pepper}", :cost => self.class.stretches).to_s
end

@@ stretches默认值为10(lib / devise.rb:71),不会被我的初始化程序覆盖

@@stretches defaults to 10 (lib/devise.rb:71) and isn't overridden by my initializer

@@ pepper默认为nil(lib / devise.rb:148),不会被我的初始化程序覆盖

@@pepper defaults to nil (lib/devise.rb:148) and isn't overridden by my initializer

我想我可以手动重新创建password_digest()但是我想我缺少有关Bcrypt的基本知识,因为即使设置了密码和密码,每次产生的哈希值也不同。

I thought I could manually re-create password_digest() but I think I'm missing something fundamental about Bcrypt because even with setting password and stretches, the resulting hash is different every time.

有什么想法吗?谢谢您的帮助!

Any ideas? Thanks for your help!

推荐答案

好消息和坏消息。

以下操作可以手动创建用户密码。

The following works to create your user's password manually.

 pepper = nil
 cost = 10
 encrypted_password = ::BCrypt::Password.create("#{password}#{pepper}", :cost => cost).to_s

您可以在设计初始化器中找到所需的胡椒和成本。使用Devise的 valid_password?确认了此方法。方法。

You can find your pepper and cost in your devise initializer. This method was confirmed using Devise's "valid_password?" method.

我试图避免出现 User.new(password:密码)。encrypted_pa​​ssword是因为速度。非常慢。在执行导入任务的所有其他步骤时,我有意避免了此操作。

The entire reason I was trying to avoid "User.new(password: password).encrypted_password" was because of speed. It's terribly slow. With all my other pieces of my import task, I've intentionally avoided this.

但是事实证明,这里的主要成本不是实例化User对象,而是BCrypt本身。直接使用BCrypt时,速度提升几乎没有,因为它是故意设计的很慢。

But as it turns out, the major cost here is not instantiating a User object -- but BCrypt itself. There is very little noticeable speed boost when using BCrypt directly because it's intentionally designed to be slow.

我的最终答案:吸干它,运行rake脚本,找到一个饮料。

My final answer: suck it up, run the rake script, go find a beverage.

这篇关于设计:手动加密密码并直接存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆