开发者

ActiveSupport::SecureRandom.hex question? Rails and Ruby

开发者 https://www.devze.com 2023-04-03 02:59 出处:网络
I have a question regarding the ActiveSupport::SecureRandom class\\library. http://apidock.com/rails/ActiveSupport/SecureRandom

I have a question regarding the ActiveSupport::SecureRandom class\library.

http://apidock.com/rails/ActiveSupport/SecureRandom

I'm writing an application that might need some Random tokens like those generated by Secure开发者_开发知识库Random.

What about the Uniqueness of these tokens? Are these Tokens Unique in nature or should I be better off using a Unique constraint on my DB Column?

Thanks!


Note the page you linked, which says that this module matches in interface (and implementation, at least in the case of one particular version) to the one at http://rubydoc.info/stdlib/securerandom/1.9.2/SecureRandom where you can find more details.

There is no inherent uniqueness in the results of such calls. Of course, given that the system is seeded well and is pseudorandom as claimed, the chance of collisions should be as small as suggested by combinatorics. This is the "Birthday Paradox", and in particular the chances of a collision correspond to a chances of a successful "Birthday Attack" ( http://en.wikipedia.org/wiki/Birthday_attack ), and you can find more details on Wikipedia. Not to say that practical pseudorandomness gives strict guarantees, but it would be believed to come close.

If you specifically need uniqueness, you need to enforce this yourself. This is not so easy to do, and you need to be careful that you are achieving the conditions you expect. You also need to be sure that you are covering all possibilities, and that if you do -- on relatively rare occasion -- generate a duplicate token, you can handle it.


You shouldn't use ActiveSupport::SecureRandom (deprecated), use Ruby's one: SecureRandom

That being said, of course they are not unique, but it is not really important: If you just need to generate a totally unique uid in your models, you can use a variation of the following code:

before_create :generate_uid

def generate_uid
    begin
        uid = SecureRandom.hex(12)
    end while SomeModel.where(:uid => uid).exists?
    self.uid = uid
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号