首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >密码安全浮点

密码安全浮点
EN

Stack Overflow用户
提问于 2016-01-03 10:47:10
回答 1查看 1K关注 0票数 7

如何在Javascript中生成密码安全浮点数?

这应该是Math.random的插件,范围为(0,1),但在密码上是安全的.示例用法

代码语言:javascript
复制
cryptoFloat.random();
0.8083966837153522

确保javascript中的随机数字安全?展示了如何创建加密安全的Uint32Array。也许这个可以被转换成浮子?

  • Mozilla Uint32Array文档并不完全清楚如何从int转换。
  • 谷歌也不是重点所在。
  • Float32Array.from(someUintBuf);总是给出一个完整的数字。
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-03 14:58:45

由于下面的代码非常简单,并且是函数等价于除法,所以这里是改变位元的交替方法。(这段代码是从@T.J.Crowder的非常有用的答案中复制和修改的)。

代码语言:javascript
复制
// A buffer with just the right size to convert to Float64
let buffer = new ArrayBuffer(8);

// View it as an Int8Array and fill it with 8 random ints
let ints = new Int8Array(buffer);
window.crypto.getRandomValues(ints);

// Set the sign (ints[7][7]) to 0 and the
// exponent (ints[7][6]-[6][5]) to just the right size 
// (all ones except for the highest bit)
ints[7] = 63;
ints[6] |= 0xf0;

// Now view it as a Float64Array, and read the one float from it
let float = new DataView(buffer).getFloat64(0, true) - 1; 
document.body.innerHTML = "The number is " + float;

解释:

IEEE754双级的格式为1符号位(ints[7][7]),11指数位(ints[7][6]ints[6][5]),其余为尾数(包含值)。要计算的公式是

若要将因子设置为1,指数需要为1023。它有11位,因此最高阶位给出2048位.这需要设置为0,其他位设置为1。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34575635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档