`
jsntghf
  • 浏览: 2482947 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

rails中的SecureRandom

阅读更多

youtube之类的视频网站的11位随机id是如何生成的?类似于:http://www.youtube.com/watch?v=fY4Epc2XSGc 中的fY4Epc2XSGc

很多人都是自己实现安全随机数,类似以下的代码:

require 'digest/sha1'

def generate_temporary_password
    self.password = Digest::SHA1.hexdigest(Time.now.to_s.split(//).sort_by{rand}.join)
end

 

其实,rails已经为你做好了这一切。

你可以像这样去使用它:

require 'active_support/secure_random'

ActiveSupport::SecureRandom.hex(10)
=> "8a2cf0a838e64f6f85d1"
ActiveSupport::SecureRandom.base64(10)
=> "fUL81hGd77YyGg=="

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics