SHA-256 cryptographic hash function implementation for TypeScript and JavaScript
npx @tessl/cli install tessl/npm-stablelib--sha256@2.0.00
# @stablelib/sha256
1
2
@stablelib/sha256 provides a TypeScript implementation of the SHA-256 cryptographic hash function. It offers both streaming (incremental) and one-shot hashing capabilities with state serialization support for optimization in HMAC/PBKDF2 scenarios.
3
4
## Package Information
5
6
- **Package Name**: @stablelib/sha256
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @stablelib/sha256`
10
11
## Core Imports
12
13
```typescript
14
import { SHA256, hash, DIGEST_LENGTH, BLOCK_SIZE } from "@stablelib/sha256";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { SHA256, hash, DIGEST_LENGTH, BLOCK_SIZE } = require("@stablelib/sha256");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { hash, SHA256 } from "@stablelib/sha256";
27
28
// One-shot hashing (recommended for simple use cases)
29
const data = new TextEncoder().encode("Hello, World!");
30
const digest = hash(data);
31
console.log(digest); // Uint8Array(32) containing the hash
32
33
// Streaming hashing (for large data or incremental processing)
34
const hasher = new SHA256();
35
hasher.update(new TextEncoder().encode("Hello, "));
36
hasher.update(new TextEncoder().encode("World!"));
37
const streamDigest = hasher.digest();
38
console.log(streamDigest); // Same result as one-shot hashing
39
40
// Reusing hasher instance
41
hasher.reset();
42
hasher.update(data);
43
const reusedDigest = hasher.digest();
44
```
45
46
## Architecture
47
48
@stablelib/sha256 is built around two main patterns:
49
50
- **Functional API**: The `hash()` function for simple one-shot hashing operations
51
- **Class-based API**: The `SHA256` class for streaming operations, state management, and advanced use cases like HMAC/PBKDF2 optimization
52
- **Memory Safety**: Automatic buffer wiping and secure cleanup to prevent sensitive data leakage
53
- **State Serialization**: Save/restore functionality for cryptographic protocol optimization
54
55
## Capabilities
56
57
### Constants
58
59
Standard SHA-256 algorithm constants for reference and validation.
60
61
```typescript { .api }
62
/** Length of SHA-256 hash output in bytes (always 32) */
63
export const DIGEST_LENGTH: number;
64
65
/** Block size used by SHA-256 algorithm in bytes (always 64) */
66
export const BLOCK_SIZE: number;
67
```
68
69
### One-Shot Hashing
70
71
Convenience function for simple hashing operations without managing state.
72
73
```typescript { .api }
74
/**
75
* Computes SHA-256 hash of the input data
76
* @param data - Input data to hash
77
* @returns SHA-256 hash digest (32 bytes)
78
*/
79
function hash(data: Uint8Array): Uint8Array;
80
```
81
82
**Usage Example:**
83
84
```typescript
85
import { hash } from "@stablelib/sha256";
86
87
// Hash a string
88
const message = new TextEncoder().encode("Hello World");
89
const digest = hash(message);
90
91
// Hash binary data
92
const binaryData = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
93
const binaryDigest = hash(binaryData);
94
```
95
96
### Streaming Hash Operations
97
98
Main SHA-256 class for incremental hashing and advanced operations.
99
100
```typescript { .api }
101
/**
102
* SHA-256 cryptographic hash algorithm implementation
103
* Implements SerializableHash interface for state management
104
*/
105
class SHA256 {
106
/** Length of hash output (always 32) */
107
readonly digestLength: number;
108
109
/** Block size (always 64) */
110
readonly blockSize: number;
111
112
/** Creates new SHA-256 instance with initialized state */
113
constructor();
114
115
/**
116
* Resets hash state making it possible to re-use this instance to hash other data
117
* @returns this instance for method chaining
118
*/
119
reset(): this;
120
121
/**
122
* Cleans internal buffers and resets hash state
123
* Securely wipes sensitive data from memory
124
*/
125
clean(): void;
126
127
/**
128
* Updates hash state with the given data
129
* @param data - Input data to add to hash
130
* @param dataLength - Number of bytes to read from data (defaults to data.length)
131
* @returns this instance for method chaining
132
* @throws Error when trying to update already finalized hash
133
*/
134
update(data: Uint8Array, dataLength: number = data.length): this;
135
136
/**
137
* Finalizes hash state and puts hash into output buffer
138
* If hash was already finalized, puts the same value
139
* @param out - Output buffer to write hash to (must be at least 32 bytes)
140
* @returns this instance for method chaining
141
*/
142
finish(out: Uint8Array): this;
143
144
/**
145
* Returns the final hash digest
146
* @returns SHA-256 hash digest as new Uint8Array (32 bytes)
147
*/
148
digest(): Uint8Array;
149
}
150
```
151
152
**Usage Examples:**
153
154
```typescript
155
import { SHA256 } from "@stablelib/sha256";
156
157
// Basic streaming hashing
158
const hasher = new SHA256();
159
hasher.update(new TextEncoder().encode("Part 1"));
160
hasher.update(new TextEncoder().encode("Part 2"));
161
const result = hasher.digest();
162
163
// Processing large data in chunks
164
const largeHasher = new SHA256();
165
const chunkSize = 1024;
166
for (let i = 0; i < largeData.length; i += chunkSize) {
167
const chunk = largeData.slice(i, i + chunkSize);
168
largeHasher.update(chunk);
169
}
170
const largeResult = largeHasher.digest();
171
172
// Reusing hasher for multiple operations
173
const reusableHasher = new SHA256();
174
reusableHasher.update(data1);
175
const hash1 = reusableHasher.digest();
176
177
reusableHasher.reset(); // Reset for next operation
178
reusableHasher.update(data2);
179
const hash2 = reusableHasher.digest();
180
181
// Cleanup when done
182
reusableHasher.clean();
183
```
184
185
### State Serialization
186
187
Advanced functionality for HMAC/PBKDF2 optimization where hash state needs to be saved and restored.
188
189
```typescript { .api }
190
/**
191
* State serialization methods for performance optimization in cryptographic protocols
192
*/
193
interface SHA256StateManagement {
194
/**
195
* Returns hash state for later restoration
196
* Only works with unfinished hash state
197
* @returns Serializable state object
198
* @throws Error if hash is already finished
199
*/
200
saveState(): SavedState;
201
202
/**
203
* Restores previously saved hash state
204
* @param savedState - State object returned by saveState()
205
* @returns this instance for method chaining
206
*/
207
restoreState(savedState: SavedState): this;
208
209
/**
210
* Securely cleans saved state object
211
* @param savedState - State object to clean
212
*/
213
cleanSavedState(savedState: SavedState): void;
214
}
215
216
/**
217
* Serializable state object for save/restore operations
218
*/
219
type SavedState = {
220
/** Internal hash state */
221
state: Int32Array;
222
/** Buffered data (undefined if no buffered data) */
223
buffer: Uint8Array | undefined;
224
/** Length of buffered data */
225
bufferLength: number;
226
/** Total bytes processed */
227
bytesHashed: number;
228
};
229
```
230
231
**Usage Example:**
232
233
```typescript
234
import { SHA256 } from "@stablelib/sha256";
235
236
// HMAC optimization pattern
237
const hasher = new SHA256();
238
hasher.update(hmacKeyPadding); // Process key padding
239
240
// Save state after key processing
241
const keyState = hasher.saveState();
242
243
// First message
244
hasher.update(message1);
245
const hash1 = hasher.digest();
246
247
// Restore state for second message (reuse key processing)
248
hasher.restoreState(keyState);
249
hasher.update(message2);
250
const hash2 = hasher.digest();
251
252
// Clean up saved state
253
hasher.cleanSavedState(keyState);
254
hasher.clean();
255
```
256
257
## Error Handling
258
259
The SHA-256 implementation includes proper error handling for invalid operations:
260
261
- **Update after finalization**: Attempting to call `update()` on a finalized hash throws an error
262
- **Save finished state**: Attempting to call `saveState()` on a finished hash throws an error
263
264
```typescript
265
import { SHA256 } from "@stablelib/sha256";
266
267
const hasher = new SHA256();
268
hasher.update(data);
269
const digest = hasher.digest(); // Hash is now finalized
270
271
try {
272
hasher.update(moreData); // This will throw
273
} catch (error) {
274
console.error("Cannot update finalized hash:", error.message);
275
}
276
277
try {
278
hasher.saveState(); // This will also throw
279
} catch (error) {
280
console.error("Cannot save finished state:", error.message);
281
}
282
```
283
284
## Performance Considerations
285
286
- Use the `hash()` function for simple one-shot operations
287
- Use the `SHA256` class for streaming large data or when you need to reuse the hasher
288
- Always call `clean()` when done to ensure secure memory cleanup
289
- Use state serialization only for specific cryptographic protocols like HMAC/PBKDF2
290
- The implementation is optimized for processing data in 64-byte blocks