Logo

Programming-Idioms

  • Java
  • Pascal
  • Dart
  • Ruby
  • Python

Idiom #318 Cryptographically secure random number

Assign to the integer x a random number between 0 and 17 (inclusive), from a crypto secure random number generator.

import secrets
x = secrets.randbelow(18)
import secrets
x = secrets.choice(range(0, 18))
require 'securerandom'
x = SecureRandom.rand(0..17)
import "crypto/rand"
import "math/big"
bi, err := rand.Int(rand.Reader, big.NewInt(18))
x := int(bi.Int64())

crypto/rand.Int works with big ints, and the secure RNG Reader.

New implementation...
< >
programming-idioms.org