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

278
Visualizações
Javascript: How to select a random element from an array securely?

There are about million questions like this, but each and every answer I saw just uses Math.random() (and in the rare case where someone has managed to use crypto.getRandomValues(), it's incredibly biased), but I need something that's cryptographically secure. I'm looking especially something like Python's secrets.randbelow(). Even better if there's a counterpart to secrets.choice(). Is there anything like that available in the standard Javascript without jQuery or other insanely large and complex dependencies? I couldn't find anything from Mozilla's documentation either.

Or should I just implement it myself? Would something like the following work or is there something I have completely missed?

//Return a random int in the range [0, n).
function randbelow(n) {
  if (n < 1) {
    throw 'Upper bound must be positive.';
  }
  if (n === 1) {
    return 0;
  }
  const maxsize = 2 ** 32;
  if (n > maxsize) {
    throw 'Only unsigned 32-bit integers are supported.';
  }
  const rem = maxsize % n;
  const limit = maxsize - rem;
  let r;
  do {
    r = crypto.getRandomValues(new Uint32Array(1))[0];
  } while (r >= limit);
  return r % n;
}

// test
var arr = ['item1', 'item2', 'item3'];
console.log(arr[randbelow(arr.length)]);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

TLDR;

import { randomInt } from 'https://cdn.jsdelivr.net/npm/random-browser';

console.log('Random number chosen from (0, 1, 2): ' + randomInt(3));

Since every "answer" on this site basically boiled down to one of the following:

  1. Math.random().
  2. Doing something completely wrong like using "randomness" from mouse movement.
  3. Importing megabytes of random dependencies that haven't been updated in years.
  4. Not understanding modulo bias.

I wrote couple of functions that mimic crypto module from Node.js and borrow ideas from Python's secrets module. The whole thing is around one kilobyte without any other dependencies. I still find it kinda crazy that in 2022 JavaScript doesn't offer any way to natively generate cryptographically random integers.

<script type="module">
import { choice, randomBits, randomBytes, randomInt, tokenHex } from 'https://cdn.jsdelivr.net/npm/random-browser';

console.log('Pick a random fruit from array: ' + choice(['Apple', 'Banana', 'Orange']));
console.log('Pick a random character from string: ' + choice('ABCDEF'));
console.log('Random integer with 4 random bits (<16): ' + randomBits(4));
console.log('3 random bytes e.g. [218, 82, 127]: ' + randomBytes(3));
console.log('Random number chosen from (0, 1, 2): ' + randomInt(3));
console.log('The dice rolled: ' + randomInt(1, 7));
console.log('32 character hexadecimal string from 16 random bytes: ' + tokenHex(16));
</script>

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