random_bytes

random_bytes(int $length): string

Generates cryptographically secure random bytes (for tokens, keys, salts and the like).

C C23

C23
#include <stdio.h>
#include <string.h>

// read n random bytes from /dev/urandom (Linux/macOS universal)
static int fill_random(unsigned char *buf, int n) {
    FILE *f = fopen("/dev/urandom", "rb");
    if (f == NULL) return 0;
    int got = (int)fread(buf, 1, (size_t)n, f);
    fclose(f);
    return got == n;
}

int main(void) {
    unsigned char a[16], b[16];
    if (!fill_random(a, 16) || !fill_random(b, 16)) return 1;
    printf("filled=%d\n", 1);
    printf("different=%s\n", memcmp(a, b, 16) != 0 ? "true" : "false");
    return 0;
}
Output
filled=1
different=true

C++ C++26

C++26
#include <cstring>
#include <iostream>
#include <random>

int main() {
    std::random_device device;
    unsigned char a[16], b[16];
    for (int i = 0; i < 16; i++) {
        a[i] = static_cast<unsigned char>(device());
        b[i] = static_cast<unsigned char>(device());
    }
    std::cout << "filled=1\n";
    std::cout << "different=" << (std::memcmp(a, b, 16) != 0 ? "true" : "false") << "\n";
    return 0;
}
Output
filled=1
different=true

C# v11.0.100

v11.0.100
using System.Security.Cryptography;

byte[] a = new byte[16];
byte[] b = new byte[16];
RandomNumberGenerator.Fill(a);
RandomNumberGenerator.Fill(b);
Console.WriteLine($"filled={(a.Length == 16 && b.Length == 16 ? 1 : 0)}");
Console.WriteLine($"different={!a.SequenceEqual(b)}");
Output
filled=1
different=True

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"crypto/rand"
	"fmt"
)

func main() {
	a := make([]byte, 16)
	b := make([]byte, 16)
	if _, err := rand.Read(a); err != nil {
		panic(err)
	}
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	fmt.Printf("filled=%d\n", 1)
	fmt.Printf("different=%v\n", !bytes.Equal(a, b))
}
Output
filled=1
different=true

Java v27.0.1

v27.0.1
import java.security.SecureRandom;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        SecureRandom random = new SecureRandom();
        byte[] a = new byte[16];
        byte[] b = new byte[16];
        random.nextBytes(a);
        random.nextBytes(b);
        System.out.println("filled=" + (a.length == 16 && b.length == 16 ? 1 : 0));
        System.out.println("different=" + (!Arrays.equals(a, b)));
    }
}
Output
filled=1
different=true

JavaScript v26.13.1

v26.13.1
const { randomBytes } = require("node:crypto");
const a = randomBytes(16);
const b = randomBytes(16);
console.log(`filled=${a.length === 16 && b.length === 16 ? 1 : 0}`);
console.log(`different=${!a.equals(b)}`);
console.log(`hex_len=${a.toString("hex").length}`);
Output
filled=1
different=true
hex_len=32

PHP v8.6.0

v8.6.0
// random_bytes output differs every run — the example asserts only deterministic properties:
// correct length (always true) and two calls differing (128-bit collision ~2.9e-39, treated as never)
$a = random_bytes(16);
$b = random_bytes(16);
echo "filled=" . (strlen($a) === 16 && strlen($b) === 16 ? 1 : 0) . "\n";
echo "different=" . json_encode($a !== $b) . "\n";
echo "hex_len=" . strlen(bin2hex($a));
Output
filled=1
different=true
hex_len=32

Python v3.15.2

v3.15.2
import secrets

a = secrets.token_bytes(16)
b = secrets.token_bytes(16)
print(f"filled={1 if len(a) == 16 and len(b) == 16 else 0}")
print(f"different={a != b}")
print(f"hex_len={len(a.hex())}")
Output
filled=1
different=True
hex_len=32

Rust v1.99.1

v1.99.1
use rand::rngs::OsRng;
use rand::RngCore;

fn main() {
    let mut a = [0u8; 16];
    let mut b = [0u8; 16];
    OsRng.fill_bytes(&mut a);
    OsRng.fill_bytes(&mut b);
    println!("filled={}", 1);
    println!("different={}", a != b);
    println!("hex_len={}", a.iter().map(|byte| format!("{:02x}", byte)).collect::<String>().len());
}
Output
filled=1
different=true
hex_len=32

TypeScript v26.13.1

v26.13.1
import { randomBytes } from "node:crypto";
const a = randomBytes(16);
const b = randomBytes(16);
console.log(`filled=${a.length === 16 && b.length === 16 ? 1 : 0}`);
console.log(`different=${!a.equals(b)}`);
console.log(`hex_len=${a.toString("hex").length}`);
Output
filled=1
different=true
hex_len=32

Language differences

C: no CSPRNG in the standard library — the example reads /dev/urandom; production should use platform APIs (getrandom(2)/BCryptGenRandom/SecRandomCopyBytes); bytes from rand() are entirely unfit for keys.

C++: random_device fills a byte array word by word (example); there is no direct 'N bytes' interface in the standard library.

C#: RandomNumberGenerator.Fill(bytes) is the modern form (the legacy Create()/GetBytes still work); output length equals the array length.

Go: crypto/rand.Read(buf) fills at once (example); errors must be handled; there is no length-parameter failure path (length follows buf).

Java: SecureRandom.nextBytes(buf) (example); displaying bytes needs manual Base64/Hex encoding (HexFormat.of().formatHex).

JavaScript: Node's crypto.randomBytes(16) (example) returns a Buffer with toString("hex")/toString("base64") for display; browsers use crypto.getRandomValues(new Uint8Array(16)).

PHP: random_bytes requires $length ≥ 1 (0/negative throws ValueError); raw binary cannot be echoed directly — encode with bin2hex/base64_encode first. Determinism note: random bytes would print differently every run, so the example asserts only length and 'two calls differ' — a 16-byte (128-bit) collision is ~2.9×10⁻³⁹, treated as never; the hex length 32 is always true.

Python: secrets.token_bytes(16) (example); secrets.token_hex(16)/token_urlsafe(16) produce encoded token strings directly (versus PHP's two-step bin2hex).

Rust: OsRng.fill_bytes(&mut buf) (example); hex via hand-written format!("{:02x}") or the hex crate.

TypeScript: same as JavaScript (example); avoid Math.random splices when minting tokens — the entropy source must uniformly go through crypto.