将元素的内部 HTML 设置为随机字符串



我需要用JavaScript将hash-paragraph.innerHTML变成随机字符串。

我试过这个:

function CreateHash() {
var randomhash = crypto.randomBytes(20).toString('hex');
randomhash.id = "randomhash";
document.getElementById("hash-paragraph").innerHTML = document.getElementById("randomhash").value;
}
<p id="hash-paragraph">This should be random string</p>
<input type="submit" name="hash-click" onclick="CreateHash()">

我是遗漏了一些行,还是var randomhash = crypto.randomBytes(20).toString('hex');走错了路?

Web Crypto API标准中没有randomBytes方法。这是一个仅在Crypto NodeJS模块上可用的方法。在这种情况下,等价物将是crypto.getRandomValues()。MDN提供了有关它的更多信息。

编辑:crypto.getRandomValues()方法需要一个TypedArray作为参数来提供熵值。我附上一个CodePen示例,展示如何生成它并将结果转换为适合您需要的十六进制格式。

最新更新