Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
Convert crypto.randomBytes() to 8 digit random integer

In my node.js server side code, while trying to create 8 digit random number, the result is not as expected.

I tried below code,

const crypto = require('crypto');
var token = crypto.randomBytes(8);

console.log(token);

Still it returns bufferred bytearray which is <Buffer 1d c3 02 b1 d1 0b e9 dc>. Tried a lot of methods to convert that byte array to 8 digit number like 98988348(Not a hexadecimal one).

But still not able to get the 8 Digit random number.

Note:Don't want to use Math.random() here.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

crypto.randomInt (Node.js v14.10+/v12.19+)

As of Node.js v14.10 (and v12.19), the crypto module exports a randomInt([min], max, [callback]) function which returns a random integer n such that min <= n < max. This function inherits all of the security benefits that the crypto module as a whole provides.

So to get a random 8 digit integer, you'd be looking to invoke the randomInt function with a min value of 10000000 and a max of 100000000:

const { randomInt } = require('crypto');

const n = randomInt(10000000, 100000000);

crypto.randomBytes

An alternative that doesn't have strict Node.js version requirements would be to convert your buffer to a hex string, and then use the parseInt function specifying the base parameter as 16 (for hex).

You can then divide that parsed integer by the largest possible value (0xffffffffffffffff) to get a cryptographically-secure number between 0 and 1.

Now you just need to multiply this by (max - min) (90000000 in your case) and then add the min (10000000).

const { randomBytes } = require('crypto');

const token = crypto.randomBytes(8);
const hex = token.toString('hex');

const min = 10000000;
const max = 100000000;

let n = parseInt(hex, 16); // 0   <= n < 2^64
n /= 0xffffffffffffffff;   // 0   <= n < 1
n *= max - min;            // 0   <= n < max - min
n += min;                  // min <= n < max
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda