内容安全策略 (csp) 随机数:随机数应该有多长或多复杂
Content Security Policy (csp) nonce: how long or complex should be a nonce
我有一个使用 nonce 的网站。一切正常。但是随机数应该有多长或多复杂。
我的随机数生成器就是这样的:
let generateNonce = (length = 32) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let nonce = '';
for (let i = 0; i < length; i++)
nonce += chars.charAt(Math.floor(Math.random() * chars.length));
return nonce;
};
调用 generateNonce()
returns 类似于 hERnT30lr0G3Hw4b5eQCjuC423a3PcBl
。
32个字符的数字,大小写字母。这够复杂还是太长了?
请参阅 https://w3c.github.io/webappsec-csp/#security-nonces 的 CSP 规范部分,其中指出:
[nonce values] should be at least 128 bits long (before encoding), and should be generated via a cryptographically secure random number generator
题目的hERnT30lr0G3Hw4b5eQCjuC423a3PcBl
值超过了128位,没关系
但是 Math.random()
不是加密安全的; and https://security.stackexchange.com/q/181580/86150. Use Crypto.getRandomValues
相反。
在@sideshowbarker 的帮助下,随机数生成器可能是这样的 (nodejs)
// require nodes native crypto module
const crypto = require('crypto');
// create 128 bit nonce synchronously
const nonce = crypto.randomBytes(16).toString('hex');
output = 1e31b6130c5be9ef4cbab7eb38df5491
crypto.randomBytes(size[, callback])
Generates cryptographically strong pseudo-random data. The size argument is a number indicating the number of bytes to generate.
我有一个使用 nonce 的网站。一切正常。但是随机数应该有多长或多复杂。
我的随机数生成器就是这样的:
let generateNonce = (length = 32) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let nonce = '';
for (let i = 0; i < length; i++)
nonce += chars.charAt(Math.floor(Math.random() * chars.length));
return nonce;
};
调用 generateNonce()
returns 类似于 hERnT30lr0G3Hw4b5eQCjuC423a3PcBl
。
32个字符的数字,大小写字母。这够复杂还是太长了?
请参阅 https://w3c.github.io/webappsec-csp/#security-nonces 的 CSP 规范部分,其中指出:
[nonce values] should be at least 128 bits long (before encoding), and should be generated via a cryptographically secure random number generator
题目的hERnT30lr0G3Hw4b5eQCjuC423a3PcBl
值超过了128位,没关系
但是 Math.random()
不是加密安全的; and https://security.stackexchange.com/q/181580/86150. Use Crypto.getRandomValues
相反。
在@sideshowbarker 的帮助下,随机数生成器可能是这样的 (nodejs)
// require nodes native crypto module
const crypto = require('crypto');
// create 128 bit nonce synchronously
const nonce = crypto.randomBytes(16).toString('hex');
output = 1e31b6130c5be9ef4cbab7eb38df5491
crypto.randomBytes(size[, callback])
Generates cryptographically strong pseudo-random data. The size argument is a number indicating the number of bytes to generate.