生成唯一的、随机的字母数字字符串
我正在开发一个应用程序,允许用户共享简单调查的链接。为此,我想为每个调查生成唯一的 URL,因此具有如下 URL:
http://myapp.com/aBcDe1F
我希望 URL 的字母数字标识符部分是伪随机的并且有点短(6-8 个字符)。现在,生成它很容易,但如何确保它们是唯一的而且是伪随机的?我是否必须生成它,然后检查数据库查询以确保它之前没有生成过,如果没有,则重新生成另一个字符串并再次尝试相同的过程?
我知道以这种方式混淆 URL 并不能真正确保安全性,但此应用程序排除了基于密码的身份验证,因此我尝试使用伪随机字符串。
I am developing an application which allows users to share a link to a simple survey. For this, I want to generate unique URLs for each survey, so having a URL like:
http://myapp.com/aBcDe1F
I want the alpha numeric identifier part of the URL to be pseudo random and somewhat short (6-8 characters). Now, generating that is easy, but how do I ensure that they are unique but also pseudo random? Do I have to generate it, then check with a query to the database to ensure it's not been generated before, and if not, regenerate another string and try the same process again?
I am aware that obfuscating the URL this way does not really ensure security by any means, but password based authentication is ruled out for this application, so I am trying to use a pseudo random character string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的 - 我认为你必须按照你的描述去做。但要完全迂腐(嗯,我的意思是“安全”),请不要这样做:
您可以同时为两个不同用户生成相同值的可能性(非常)小。
相反,使用该值作为数据库中的主键并执行此操作
Yes - I think you have to do it as you describe. But to be completely pedantic (ummm, I mean "safe") do not do this:
There is a (very) small chance that you could generate the same value for two different users simultaneously.
Rather, use the value as a primary key within the database and do this
未指定语言,但许多语言支持创建 GUID。为什么不使用其中之一呢?
No language specified, but many languages support the creation of a GUID. Why not use one of those?
有多种方法可以实现这一点,一种常见的方法是使用当前时间并对其执行 md5() 。随后,您可以检查您的数据库是否以前使用过。通常,2 个 md5() 产生非常接近的相同字符串结果的概率非常低。
其他方法包括使用用户的 ip + 时间戳作为字符串并对其进行 md5()。
希望它有帮助(:
Well there are various ways to go about it, one common one is to use the current time and do an md5() on it. Subsequently, you may check against your database if that has been used before. Normally, the probability of having 2 md5() that produce the same string result in close proximity is pretty low.
Other methods include using the user's ip + timestamp as a string and md5() it.
Hope it helps (:
由于您没有将其用作密钥而只是随机使用字符串,因此您可以在 Java 中使用此程序:
我知道这有点低技能,还有许多其他库和代码,例如:
可以使用,但是嘿我们可以也保持简单。
Since you are not using it as a key and just for random use of string, you can use this program in Java:
I know this is a bit low skilled and many other libraries and code such as:
Can be used, but hey we can keep it simple too.