0
# scrypt-js
1
2
scrypt-js is a JavaScript implementation of the scrypt password-based key derivation function (PBKDF) designed for brute-force resistance. It provides both synchronous and asynchronous computation methods with advanced features including non-blocking execution, cancellable operations, and progress callbacks for real-time feedback during key derivation.
3
4
## Package Information
5
6
- **Package Name**: scrypt-js
7
- **Package Type**: npm
8
- **Language**: JavaScript (with TypeScript definitions)
9
- **Installation**: `npm install scrypt-js`
10
11
## Core Imports
12
13
```javascript
14
const scrypt = require("scrypt-js");
15
```
16
17
TypeScript/ES6:
18
19
```typescript
20
import * as scrypt from "scrypt-js";
21
// or
22
import { scrypt as scryptAsync, syncScrypt } from "scrypt-js";
23
```
24
25
## Basic Usage
26
27
```javascript
28
const scrypt = require("scrypt-js");
29
30
// Convert password and salt to byte arrays
31
const password = Buffer.from("myPassword", "utf8");
32
const salt = Buffer.from("mySalt", "utf8");
33
34
// Set scrypt parameters
35
const N = 1024; // CPU/memory cost
36
const r = 8; // Block size
37
const p = 1; // Parallelization
38
const dkLen = 32; // Desired key length
39
40
// Asynchronous with progress callback
41
const progressCallback = (progress) => {
42
console.log(`Progress: ${Math.round(progress * 100)}%`);
43
// Return true to cancel operation
44
return false;
45
};
46
47
scrypt.scrypt(password, salt, N, r, p, dkLen, progressCallback)
48
.then(key => {
49
console.log("Derived key:", Buffer.from(key).toString("hex"));
50
})
51
.catch(error => {
52
console.error("Error:", error);
53
});
54
55
// Synchronous (blocking)
56
const key = scrypt.syncScrypt(password, salt, N, r, p, dkLen);
57
console.log("Derived key:", Buffer.from(key).toString("hex"));
58
```
59
60
## Capabilities
61
62
### Asynchronous Key Derivation
63
64
Computes the scrypt PBKDF asynchronously using a Promise, allowing for non-blocking execution and progress monitoring.
65
66
```typescript { .api }
67
function scrypt(
68
password: ArrayLike<number>,
69
salt: ArrayLike<number>,
70
N: number,
71
r: number,
72
p: number,
73
dkLen: number,
74
callback?: ProgressCallback
75
): Promise<Uint8Array>;
76
```
77
78
**Parameters:**
79
- `password`: Password as byte array (ArrayLike<number>)
80
- `salt`: Salt as byte array (ArrayLike<number>)
81
- `N`: CPU/memory cost parameter (must be power of 2)
82
- `r`: Block size parameter
83
- `p`: Parallelization parameter
84
- `dkLen`: Desired key length in bytes
85
- `callback`: Optional callback for progress updates and cancellation
86
87
**Returns:** Promise that resolves to Uint8Array containing the derived key
88
89
**Features:**
90
- Non-blocking execution that yields control to event loop
91
- Progress callback receives values from 0 to 1
92
- Cancellable by returning `true` from progress callback (Promise rejects when cancelled)
93
- Always calls progress callback with 0 at start and 1 at completion
94
95
### Synchronous Key Derivation
96
97
Computes the scrypt PBKDF synchronously, blocking execution until completion.
98
99
```typescript { .api }
100
function syncScrypt(
101
password: ArrayLike<number>,
102
salt: ArrayLike<number>,
103
N: number,
104
r: number,
105
p: number,
106
dkLen: number
107
): Uint8Array;
108
```
109
110
**Parameters:**
111
- `password`: Password as byte array (ArrayLike<number>)
112
- `salt`: Salt as byte array (ArrayLike<number>)
113
- `N`: CPU/memory cost parameter (must be power of 2)
114
- `r`: Block size parameter
115
- `p`: Parallelization parameter
116
- `dkLen`: Desired key length in bytes
117
118
**Returns:** Uint8Array containing the derived key
119
120
**Note:** This function blocks the JavaScript event loop during computation and is not recommended for UI applications.
121
122
## Types
123
124
```typescript { .api }
125
type ProgressCallback = (progress: number) => boolean | void;
126
```
127
128
**ProgressCallback function:**
129
- `progress`: Number between 0 and 1 (inclusive) indicating completion percentage
130
- **Returns:** `true` to cancel the operation, `false` or `undefined` to continue
131
132
## Parameter Guidelines
133
134
### Security Parameters
135
136
The scrypt algorithm uses three tuning parameters that affect security and performance:
137
138
- **N (CPU/Memory Cost)**: Must be a power of 2. Higher values increase memory usage and computation time. Common values: 1024, 2048, 4096, 8192, 16384.
139
- **r (Block Size)**: Affects memory latency and bandwidth dependency. Typical value: 8.
140
- **p (Parallelization)**: Affects multi-processing dependency. Typical values: 1-4.
141
142
### Recommended Parameters
143
144
- **Interactive logins**: N=1024, r=8, p=1 (fast but less secure)
145
- **File encryption**: N=16384, r=8, p=1 (balanced security/performance)
146
- **High security**: N=32768 or higher, r=8, p=1 (slow but very secure)
147
148
## Input Encoding
149
150
**Important:** Always normalize Unicode passwords using `String.prototype.normalize('NFKC')` before converting to bytes to ensure consistent results across platforms.
151
152
```javascript
153
// Recommended password encoding
154
const password = Buffer.from("myPassword".normalize('NFKC'), "utf8");
155
const salt = Buffer.from("mySalt".normalize('NFKC'), "utf8");
156
```
157
158
## Error Handling
159
160
```javascript
161
// Async error handling
162
scrypt.scrypt(password, salt, N, r, p, dkLen)
163
.then(key => {
164
// Success
165
})
166
.catch(error => {
167
// Handle errors (invalid parameters, out of memory, etc.)
168
});
169
170
// Sync error handling
171
try {
172
const key = scrypt.syncScrypt(password, salt, N, r, p, dkLen);
173
} catch (error) {
174
// Handle errors
175
}
176
```
177
178
## Platform Compatibility
179
180
- **Node.js**: Full support via CommonJS require
181
- **Browsers**: Full support via script tag or module bundlers (IE9+)
182
- **TypeScript**: Complete type definitions included
183
- **Module Systems**: Supports CommonJS, AMD/RequireJS, and browser globals
184
- **Unicode normalization**: Requires `String.prototype.normalize()` support or polyfill (unorm package)
185
186
## Performance Considerations
187
188
- Use asynchronous version (`scrypt`) for UI applications to avoid blocking
189
- Use synchronous version (`syncScrypt`) only for server-side or CLI applications
190
- Consider using Web Workers in browsers for CPU-intensive operations
191
- Memory usage scales with N parameter - monitor for large N values
192
- Progress callback adds slight overhead but enables cancellation and UX feedback
193
194
## References
195
196
- [scrypt specification (RFC 7914)](https://tools.ietf.org/rfc/rfc7914.txt)
197
- [Unicode normalization best practices](https://en.wikipedia.org/wiki/Unicode_equivalence)