如何在node.js中生成一个nonce?

wbrvyc0a  于 2023-01-08  发布在  Node.js
关注(0)|答案(4)|浏览(158)

我需要生成一个nonce(只生成一次的数字)来删除CSP规则'unsafe-inline'和脚本的所有可信URL,从而提高CSP得分。

<script nonce="{{{nonce}}}" src="http://example.com/file.js">

我知道nonce必须是唯一的,其计算方法几乎不可能预测,它应该至少有128位(即16个字节),并以base64编码。因此,这对node.js是正确的吗?

const crypto = require('crypto');
let nonce = crypto.randomBytes(16).toString('base64');
wz3gfoph

wz3gfoph1#

只是为了确认这确实在NodeJS中对CSP随机数有效

const crypto = require('crypto');
let nonce = crypto.randomBytes(16).toString('base64');
pbgvytdp

pbgvytdp2#

我建议使用uuidhttps://www.npmjs.com/package/uuid
每个uuid正好是所需的16字节(128位),并且您的计算机被流星击中的概率比产生uuid碰撞的概率更高。

axr492tv

axr492tv3#

您可以使用内置的crypto.randomUUID()生成一个36个字符长的字符串(288位),该字符串对128位随机性进行编码

const crypto = require('crypto')
crypto.randomUUID()
'5a388e8e-09eb-4778-a242-ea663f3c7e5e'

crypto.randomUUID()文档中所述:
生成随机RFC 4122版本4 UUID。UUID是使用加密伪随机数生成器生成的。

mbzjlibv

mbzjlibv4#

It is better:

     <script nonce="{{nonce}}" .. if you use HBS
    not <script nonce="{{{nonce}}}"
    in HBS convention: {{{body}}} vs {{title}} ,{{nonce}} or {{any_rendered_var}}

And in app.js of development environment:

    const crypto=require('crypto');
    var nonce=crypto.randomBytes(16).toString("hex");
    app.get('/', function(req, res) {res.render('index',{title:'Welcome',nonce:nonce});});

That does not protect you against cross scripting, because you just rendered to nonce a random value and your app does not know about any cross scripting or why did you render the random value of nonce or nnc or any other name of the variable.

But you should use helmet npm package in production!
so in server.js:

    const crypto=require('crypto');
    var nonce=crypto.randomBytes(16).toString("hex");
    app.get('/', function(req, res) {res.render('index',{title:'Welcome',nonce:nonce});});
    //add
    const helmet = require('helmet');

The helmet would block the nonce and in a browser you will see: <script nonce="" .. because CSP helmet requires:
`<script nonce="random_value_client===csp_helmet_random_value_server" ..` 
to really prevent the cross scripting

相关问题