JavaScript

JavaScript

By DeepSource

Audit: Found insecure randomness in initialization of sensitive data JS-A1000

Security

Numbers generated by Math.random are not cryptographically secure. When using random numbers in security sensitive contexts, it is recommended to go with cryptographically secure sources of randomness.

In the browser, you can use Crypto.getRandomValues. For NodeJS environments, you can use the built-in getRandomValues from the "crypto" module.

Bad Practice

// In NodeJS
const password = `${basePassword}-${Math.random() * 1000}

// In the browser
const formData = getUserInput()
formData.password += Math.random()

Recommended

// In NodeJS
const crypto = require('crypto')
const suffix = crypto.randomBytes(seed)[0]
const password = `${basePassword}-${suffix}`

// In the browser
const formData = getUserInput()
formData.password += window.crypto.getRandomValues(seed)[0]

References