Skip to main content
European CommissionEBSI European Blockchain

Random number generation examples

Last updated on

Introduction

This document presents simple code snippets for secure random number generation. These snippets are for demonstration purposes only. For production systems, please refer to the documentation and security guidelines specific to each listed library relevant to your project.

Examples

Node.js (JavaScript / TypeScript):

// CommonJS syntax
const { randomBytes } = require("crypto");
// ESM syntax
// import { randomBytes } from "crypto";

const randomBytes = randomBytes(16);
const randomNumber = randomBytes.toString("hex");
console.log(randomNumber);

Java:

import java.security.SecureRandom;

SecureRandom random = new SecureRandom();
byte[] randomBytes = new byte[16];
random.nextBytes(randomBytes);

Kotlin:

import java.security.SecureRandom

val random = SecureRandom()
val randomBytes = ByteArray(16)
random.nextBytes(randomBytes)
val randomNumber = randomBytes.joinToString("") { "%02x".format(it) }
println(randomNumber)

Python:

import secrets
import binascii

random_bytes = secrets.token_bytes(16)
random_number = binascii.hexlify(random_bytes).decode()
print(random_number)