URL中的加密ID

时间:2010-03-15 19:17:16

标签: ruby-on-rails

我正在尝试对URL的记录ID进行哈希或加密,以致人们无法通过猜测不同的整数ID来查看各种记录。

基本上,我的网址是这样的:/ plans / 0AUTxwoGkOYfiZGd2 而不是/ plans / 304。

这样做的最佳方法是使用SHA-1来散列计划的id并将其存储在hashed_id列中以供计划使用吗?然后,覆盖to_param并添加一个finder以通过hashed_id查找?

如何确保生成的字符为0-9,a-z或A-Z?

谢谢!

3 个答案:

答案 0 :(得分:1)

> 如何确保生成的字符为0-9,a-z或A-Z?

idForURL = URI.escape((Base64.encode64(hash).strip))

我曾经encrypted the id with Blowfish,它不是超级安全,但它很方便,而且ID比GUID或SHA-1短。

require 'digest/sha1'
print Digest::SHA1.hexdigest("Let's see how long this gets.")
=> b26316a2db52609f86b540de65282b9d367e085c

答案 1 :(得分:1)

我用了 https://github.com/norman/friendly_id这样:

  # app/models/secret.rb; this would go in the model you want to obfuscate
  class Secret < ActiveRecord::Base
    has_friendly_id :code, :use_slug => true

    validates :name, :uniqueness => true

    def code
       Digest::SHA1.hexdigest self.name
    end
  end
这很简单。如果你的安全需求很严重,你可能想要一些更复杂的东西(更不用说比基本的混淆技术更多的分层),但我想分享一种开箱即用的方式来使用已经存在的宝石(甚至可能已在您的应用中使用)

答案 2 :(得分:0)

在您的模型中包括一个随机代码创建者,而不是将FriendlyId引用给它。

class Restaurant < ApplicationRecord
  extend FriendlyId
  friendly_id :random_code, use: :slugged

  def random_code
    SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
  end