Probability of collision of SecureRandom.urlsafe_base64(8) in Ruby?

回眸只為那壹抹淺笑 提交于 2019-12-05 23:57:35
Andrew says Reinstate Monica

There is a good approximation of this probability (which relates to the birthday problem). If there are k potential values and n are sampled, the probability of collision is:

k! / (k^n * (k - n)!)

The base64 method returns a base 64 string built from the inputted number of random bytes, not that number of random digits. Eight random bytes gives us k = 256^8, about 1.8446744e+19. You are generating 10,000 of these strings, so n = 10,000, which gives us a probability of 2.710498492319857e-12, which is very low.

You do not make something sure by calculation a probability, you only know how likely it might happen.

To protect yourself just add a unique index to the database column. That ensures that you cannot store duplicates in your database. The insertion will raise an ActiveRecord::InvalidStatement error when this very unlikely (see @AndrewPilser's answer) event happens.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!