0
# Random Number Generation
1
2
Cryptographically secure random number generation for keys, nonces, salts, and other security-critical values. Uses the operating system's secure random number generator.
3
4
## Capabilities
5
6
### Random Bytes
7
8
```javascript { .api }
9
/**
10
* Generates cryptographically secure random bytes
11
* @param length - Number of random bytes to generate
12
* @returns Uint8Array of random bytes
13
*/
14
function randombytes_buf(length);
15
16
/**
17
* Generates deterministic random bytes from a seed
18
* @param length - Number of bytes to generate
19
* @param seed - 32-byte seed for deterministic generation
20
* @returns Uint8Array of pseudorandom bytes
21
*/
22
function randombytes_buf_deterministic(length, seed);
23
```
24
25
**Usage Example:**
26
27
```javascript
28
// Generate random key
29
const key = sodium.randombytes_buf(32);
30
31
// Generate random nonce
32
const nonce = sodium.randombytes_buf(24);
33
34
// Generate deterministic bytes (useful for testing)
35
const seed = sodium.randombytes_buf(32);
36
const deterministicBytes1 = sodium.randombytes_buf_deterministic(64, seed);
37
const deterministicBytes2 = sodium.randombytes_buf_deterministic(64, seed);
38
// deterministicBytes1 === deterministicBytes2
39
```
40
41
### Random Integers
42
43
```javascript { .api }
44
/**
45
* Generates a random 32-bit unsigned integer
46
* @returns Random integer between 0 and 2^32-1
47
*/
48
function randombytes_random();
49
50
/**
51
* Generates a uniform random integer in range [0, upper_bound)
52
* @param upper_bound - Exclusive upper bound (must be > 0)
53
* @returns Random integer between 0 and upper_bound-1
54
*/
55
function randombytes_uniform(upper_bound);
56
```
57
58
**Usage Example:**
59
60
```javascript
61
// Generate random 32-bit integer
62
const randomInt = sodium.randombytes_random();
63
console.log(randomInt); // e.g., 3847291038
64
65
// Generate random integer in specific range
66
const diceRoll = sodium.randombytes_uniform(6) + 1; // 1-6
67
const randomIndex = sodium.randombytes_uniform(arrayLength); // 0 to arrayLength-1
68
69
// Generate random boolean
70
const randomBool = sodium.randombytes_uniform(2) === 1;
71
```
72
73
### Generator Management
74
75
```javascript { .api }
76
/**
77
* Stirs the entropy pool (generally not needed)
78
*/
79
function randombytes_stir();
80
81
/**
82
* Closes the random number generator (cleanup)
83
*/
84
function randombytes_close();
85
86
/**
87
* Sets a custom random number generator implementation
88
* @param implementation - Custom RNG implementation object
89
*/
90
function randombytes_set_implementation(implementation);
91
```
92
93
## Common Use Cases
94
95
### Cryptographic Keys
96
97
```javascript
98
// Generate keys for different algorithms
99
const secretboxKey = sodium.randombytes_buf(sodium.crypto_secretbox_KEYBYTES);
100
const authKey = sodium.randombytes_buf(sodium.crypto_auth_KEYBYTES);
101
const genericHashKey = sodium.randombytes_buf(sodium.crypto_generichash_KEYBYTES);
102
103
// Or use algorithm-specific key generators (recommended)
104
const secretboxKey2 = sodium.crypto_secretbox_keygen();
105
const authKey2 = sodium.crypto_auth_keygen();
106
```
107
108
### Nonces and IVs
109
110
```javascript
111
// Generate nonces for encryption
112
const secretboxNonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
113
const boxNonce = sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES);
114
const aeadNonce = sodium.randombytes_buf(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES);
115
```
116
117
### Salts for Password Hashing
118
119
```javascript
120
// Generate salt for password hashing
121
const salt = sodium.randombytes_buf(sodium.crypto_pwhash_SALTBYTES);
122
123
const hash = sodium.crypto_pwhash_str(
124
password,
125
sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
126
sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE
127
);
128
```
129
130
### Random Tokens and IDs
131
132
```javascript
133
// Generate session tokens
134
const sessionToken = sodium.to_hex(sodium.randombytes_buf(32));
135
136
// Generate random IDs
137
const userId = sodium.randombytes_uniform(1000000); // 0-999999
138
139
// Generate random strings (base64 encoded)
140
const randomString = sodium.to_base64(
141
sodium.randombytes_buf(32),
142
sodium.base64_variants.URLSAFE_NO_PADDING
143
);
144
```
145
146
### Sampling and Selection
147
148
```javascript
149
// Randomly select from array
150
const items = ['apple', 'banana', 'cherry', 'date'];
151
const randomItem = items[sodium.randombytes_uniform(items.length)];
152
153
// Shuffle array (Fisher-Yates)
154
function shuffle(array) {
155
const result = [...array];
156
for (let i = result.length - 1; i > 0; i--) {
157
const j = sodium.randombytes_uniform(i + 1);
158
[result[i], result[j]] = [result[j], result[i]];
159
}
160
return result;
161
}
162
163
const shuffled = shuffle(['A', 'B', 'C', 'D', 'E']);
164
```
165
166
## Testing and Deterministic Generation
167
168
For testing purposes, you can generate predictable random bytes:
169
170
```javascript
171
// Create deterministic "random" data for tests
172
const testSeed = new Uint8Array(32).fill(1); // Fixed seed
173
const testKey = sodium.randombytes_buf_deterministic(32, testSeed);
174
const testNonce = sodium.randombytes_buf_deterministic(24, testSeed);
175
176
// Same seed always produces same output
177
const sameKey = sodium.randombytes_buf_deterministic(32, testSeed);
178
// testKey === sameKey
179
```
180
181
## Security Considerations
182
183
- **Cryptographic Quality**: All functions use cryptographically secure random sources
184
- **Seeding**: The generator is automatically seeded from the OS entropy pool
185
- **Thread Safety**: Functions are thread-safe and can be called from multiple threads
186
- **Deterministic Generation**: Only use `randombytes_buf_deterministic()` for testing, never for production keys
187
- **Upper Bound**: `randombytes_uniform()` uses rejection sampling to ensure uniform distribution
188
- **Entropy**: The OS random source should have sufficient entropy - avoid using in very early boot scenarios