0
# Cryptographic Operations
1
2
Generate random data and perform key derivation with promise support. Provides modern async/await compatibility for Node.js crypto operations.
3
4
## Capabilities
5
6
### Random Data Generation
7
8
Generate cryptographically secure random data.
9
10
```javascript { .api }
11
/**
12
* Generate cryptographically strong random data
13
* @param size - Number of bytes to generate
14
* @returns Promise resolving to Buffer containing random bytes
15
*/
16
function randomBytes(size): Promise<Buffer>;
17
18
/**
19
* Generate pseudo-random data (less secure than randomBytes)
20
* @param size - Number of bytes to generate
21
* @returns Promise resolving to Buffer containing pseudo-random bytes
22
*/
23
function pseudoRandomBytes(size): Promise<Buffer>;
24
```
25
26
### Key Derivation
27
28
Derive cryptographic keys using PBKDF2 algorithm.
29
30
```javascript { .api }
31
/**
32
* PBKDF2 key derivation function
33
* @param password - Password string or Buffer
34
* @param salt - Salt string or Buffer
35
* @param iterations - Number of iterations
36
* @param keylen - Desired key length in bytes
37
* @param digest - Digest algorithm (e.g., 'sha256', 'sha512')
38
* @returns Promise resolving to derived key Buffer
39
*/
40
function pbkdf2(password, salt, iterations, keylen, digest): Promise<Buffer>;
41
```
42
43
**Usage Examples:**
44
45
```javascript
46
const crypto = require('mz/crypto');
47
48
// Generate random data
49
async function generateRandomData() {
50
try {
51
// Generate 16 random bytes
52
const randomData = await crypto.randomBytes(16);
53
console.log('Random hex:', randomData.toString('hex'));
54
console.log('Random base64:', randomData.toString('base64'));
55
56
// Generate larger amounts
57
const largeRandom = await crypto.randomBytes(256);
58
console.log('Large random data length:', largeRandom.length);
59
60
} catch (error) {
61
console.error('Random generation failed:', error);
62
}
63
}
64
65
// Generate pseudo-random data (faster but less secure)
66
async function generatePseudoRandom() {
67
try {
68
const pseudoData = await crypto.pseudoRandomBytes(32);
69
console.log('Pseudo-random hex:', pseudoData.toString('hex'));
70
} catch (error) {
71
console.error('Pseudo-random generation failed:', error);
72
}
73
}
74
75
// Key derivation
76
async function deriveKey() {
77
try {
78
const password = 'user-password';
79
const salt = await crypto.randomBytes(16); // Generate random salt
80
81
// Derive key using PBKDF2
82
const derivedKey = await crypto.pbkdf2(
83
password, // Password
84
salt, // Salt
85
100000, // Iterations (higher = more secure but slower)
86
32, // Key length in bytes
87
'sha256' // Hash algorithm
88
);
89
90
console.log('Derived key:', derivedKey.toString('hex'));
91
console.log('Salt used:', salt.toString('hex'));
92
93
} catch (error) {
94
console.error('Key derivation failed:', error);
95
}
96
}
97
98
// Callback support is still available
99
crypto.randomBytes(8, (err, buffer) => {
100
if (err) {
101
console.error('Error:', err);
102
} else {
103
console.log('Random bytes:', buffer.toString('hex'));
104
}
105
});
106
107
// Practical example: Generate API key
108
async function generateApiKey() {
109
try {
110
const key = await crypto.randomBytes(32);
111
const apiKey = key.toString('base64url'); // URL-safe base64
112
console.log('Generated API key:', apiKey);
113
return apiKey;
114
} catch (error) {
115
throw new Error('Failed to generate API key: ' + error.message);
116
}
117
}
118
119
// Practical example: Password hashing preparation
120
async function preparePasswordHash(password) {
121
try {
122
// Generate salt
123
const salt = await crypto.randomBytes(16);
124
125
// Derive key (this would be stored as the password hash)
126
const hash = await crypto.pbkdf2(password, salt, 100000, 64, 'sha512');
127
128
return {
129
salt: salt.toString('hex'),
130
hash: hash.toString('hex')
131
};
132
} catch (error) {
133
throw new Error('Password hashing failed: ' + error.message);
134
}
135
}
136
```
137
138
## Error Handling
139
140
All crypto functions will reject with an error when:
141
- Invalid parameters are provided
142
- System entropy is insufficient (rare)
143
- The requested size is too large
144
- Invalid digest algorithm is specified (for pbkdf2)
145
146
```javascript
147
const crypto = require('mz/crypto');
148
149
async function handleCryptoErrors() {
150
try {
151
// This will fail if size is negative or too large
152
await crypto.randomBytes(-1);
153
} catch (error) {
154
console.error('Invalid size:', error.message);
155
}
156
157
try {
158
// This will fail with invalid digest
159
await crypto.pbkdf2('password', 'salt', 1000, 32, 'invalid-digest');
160
} catch (error) {
161
console.error('Invalid digest:', error.message);
162
}
163
}
164
```
165
166
## Security Considerations
167
168
- **Use `randomBytes()` for cryptographic purposes**: It provides cryptographically secure random data
169
- **Avoid `pseudoRandomBytes()` for security-critical applications**: It's faster but less secure
170
- **Use sufficient PBKDF2 iterations**: At least 100,000 iterations recommended for password hashing
171
- **Always use random salts**: Generate a new salt for each password/key derivation
172
- **Choose appropriate key lengths**: 32 bytes (256 bits) minimum for symmetric keys
173
174
## Implementation Notes
175
176
- Uses `thenify-all` to wrap native crypto methods
177
- Maintains complete compatibility with native crypto behavior
178
- Supports both promise and callback interfaces
179
- All functions return Buffers (use `.toString()` methods for string conversion)
180
- Error behavior matches native crypto module exactly