Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda