Clo*_*nch 5 javascript cryptography
Javascript 中是否有加密安全伪随机数生成器 (CSPRNG)?
我知道我可以使用生成伪随机数
Math.random();
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
Run Code Online (Sandbox Code Playgroud)
在Python中我会使用secrets()而不是random().
import secrets alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(8))
Run Code Online (Sandbox Code Playgroud)
在 Go 中我会使用crypto.randpackage 而不是math/randpackage。
package main
import (
"bytes"
"crypto/rand"
"fmt"
)
func main() {
c := 10
b := make([]byte, c)
_, err := rand.Read(b)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(bytes.Equal(b, make([]byte, c)))
}
Run Code Online (Sandbox Code Playgroud)
javascript 中有等价的吗?
在浏览器中,您可以查看window.crypto.getRandomValues. 请参阅此处的详细信息。
const array = new Uint32Array(10);
window.crypto.getRandomValues(array);
Run Code Online (Sandbox Code Playgroud)
在节点中,查看crypto 模块。
const crypto = require('crypto');
crypto.randomBytes(20, (err, buffer) => {
const token = buffer.toString('hex');
console.log(token);
});
Run Code Online (Sandbox Code Playgroud)
如果您有浏览器支持问题,请考虑查看像这样的npm 包。注意:我从未使用过这个,所以我不能保证它。