Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a nonce in node.js?

I need to generate a nonce (number generated only once) to remove the CSP rule 'unsafe-inline' and all the trusted URLs for scripts, improving the CSP score. Thus I need to have in the HTML

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

I know the nonce must be unique with a method of calculation almost impossible to predict, it should have at least 128 bits (hence 16 bytes), and be encoded in base64. Is therefore this correct for node.js?

const crypto = require('crypto'); let nonce = crypto.randomBytes(16).toString('base64'); 
like image 225
João Pimentel Ferreira Avatar asked Apr 27 '18 20:04

João Pimentel Ferreira


People also ask

What is a nonce generator?

A Nonce ("Number-used-ONCE") is a randomly-generated number that is used to randomize the signed hash blobs (SHSH blobs) that Apple uses to sign firmwares. it is used with the APTicket (firmware signing ticket), the BBTicket (baseband signing ticket), and the SEPTicket (SEP signing ticket).

What is nonce in Javascript?

Description. The nonce attribute is useful to allow-list specific elements, such as a particular inline script or style elements. It can help you to avoid using the CSP unsafe-inline directive, which would allow-list all inline scripts or styles.

What is CSP nonce?

Generate a nonce for CSP # A nonce is a random number used only once per page load. A nonce-based CSP can only mitigate XSS if the nonce value is not guessable by an attacker. A nonce for CSP needs to be: A cryptographically strong random value (ideally 128+ bits in length)

What is a nonce in Python?

Introduction. A nonce is a number that uniquely identifies each call to the REST API private endpoints.


2 Answers

Just to confirm that indeed this does work in NodeJS for CSP nonces

const crypto = require('crypto'); let nonce = crypto.randomBytes(16).toString('base64'); 
like image 91
João Pimentel Ferreira Avatar answered Sep 28 '22 14:09

João Pimentel Ferreira


I suggest using uuid for this: https://www.npmjs.com/package/uuid

Each uuid is exactly 16 bytes (128 bits) as desired, and you have a higher probability of your computer being hit by a meteor than generating a uuid collision.

like image 40
Mitch Talmadge Avatar answered Sep 28 '22 14:09

Mitch Talmadge