JavaScript 中的安全随机?
JavaScript 中是否有类似于 SecureRandom.hex() 的 (ruby) 函数可以为我生成随机哈希?
Is there a SecureRandom.hex()
-like (ruby) function in JavaScript which generates a random hash for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用以下关键字将这个问题作为顶级搜索引擎结果:
因此,我认为最好用今天(2019)可用的答案更新这篇文章:
下面的代码片段采用 < a href="https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues" rel="nofollow noreferrer">
Crypto.getRandomValues()
用于获取据说是的随机值,因此,我们有:
现在,下面是一个有趣的小十六进制编码器,我使用一些 Array 函数进行循环,将其作为单行代码编写:
最后,如果您想将上面的两个结合起来以生成随机数哈希值,您只需相应地交换和调整
.map()
函数,然后将其打包,如下所示:快乐编码!
编辑:事实证明,我最终在自己的项目中需要这个,该项目还实现了上一个示例中建议的 TODO(延迟加载),所以我们开始:
或者如果您真的很喜欢冒险...... 扩展
Math
或覆盖
Math.random()
以进行直接替换是否适合您的应用程序或目标受众,这纯粹是留给实现者的学术练习。请务必先咨询您的建筑师!当然要在这里获得麻省理工学院的许可:)I was led to this question as a top search engine result using the following keywords:
As such, I thought it would be good to update this post with a working answer available today (2019):
The snippet below employs
Crypto.getRandomValues()
for sourcing random values said to be,Thus, we have:
Now, below is a fun little hex-encoder I cooked up as a one-liner using some
Array
functions for looping:Finally, if you want to combine the two above for generating random hashes, you can just swap out and adapt the
.map()
function accordingly and package it up like so:Happy coding!
Edit: Turns out I ended up needing this in my own project which also implements the suggested TODO in the previous example (lazy-loading) so here we go:
Or if you're feeling really adventurous...
Whether extending
Math
or overwritingMath.random()
for a drop-in replacement is appropriate for your application or target audience is left purely as an academic exercise to the implementor. Be sure to check with your architect first! License MIT here of course :)JS 中没有这样的辅助函数。您可以使用以下方法生成相当随机的哈希值:
您可以修改它以形成 guid:
There is no such helper function in JS. You can generates a fairly random hash using:
You can modify it to form a guid: