0
# Cryptographic Utilities
1
2
Essential utility functions for byte manipulation, number conversion, validation, and cryptographic operations used throughout the library.
3
4
## Capabilities
5
6
### Byte Operations
7
8
Functions for converting between different byte representations and manipulating byte arrays.
9
10
```typescript { .api }
11
import {
12
bytesToHex, hexToBytes, concatBytes, copyBytes, equalBytes,
13
bytesToUtf8, utf8ToBytes, asciiToBytes, isBytes, ensureBytes
14
} from "@noble/curves/utils";
15
16
/**
17
* Converts byte array to hexadecimal string
18
* @param bytes - Byte array to convert
19
* @returns Lowercase hexadecimal string without 0x prefix
20
*/
21
function bytesToHex(bytes: Uint8Array): string;
22
23
/**
24
* Converts hexadecimal string to byte array
25
* @param hex - Hex string (with or without 0x prefix)
26
* @returns Byte array representation
27
*/
28
function hexToBytes(hex: string): Uint8Array;
29
30
/**
31
* Concatenates multiple byte arrays into one
32
* @param arrays - Variable number of byte arrays to concatenate
33
* @returns Single concatenated byte array
34
*/
35
function concatBytes(...arrays: Uint8Array[]): Uint8Array;
36
37
/**
38
* Creates a copy of a byte array
39
* @param bytes - Byte array to copy
40
* @returns New byte array with same contents
41
*/
42
function copyBytes(bytes: Uint8Array): Uint8Array;
43
44
/**
45
* Compares two byte arrays for equality in constant time
46
* @param a - First byte array
47
* @param b - Second byte array
48
* @returns True if arrays are equal, false otherwise
49
*/
50
function equalBytes(a: Uint8Array, b: Uint8Array): boolean;
51
52
/**
53
* Converts UTF-8 string to byte array
54
* @param str - UTF-8 string to convert
55
* @returns Byte array representation
56
*/
57
function utf8ToBytes(str: string): Uint8Array;
58
59
/**
60
* Converts byte array to UTF-8 string
61
* @param bytes - Byte array to convert
62
* @returns UTF-8 string representation
63
*/
64
function bytesToUtf8(bytes: Uint8Array): string;
65
66
/**
67
* Converts ASCII string to byte array
68
* @param ascii - ASCII string to convert
69
* @returns Byte array representation
70
*/
71
function asciiToBytes(ascii: string): Uint8Array;
72
73
/**
74
* Type guard to check if value is a Uint8Array
75
* @param a - Value to check
76
* @returns True if value is Uint8Array
77
*/
78
function isBytes(a: unknown): a is Uint8Array;
79
80
/**
81
* Ensures input is a byte array with optional length validation
82
* @param title - Description for error messages
83
* @param hex - Input that should be converted to bytes
84
* @param expectedLength - Optional expected byte length
85
* @returns Validated byte array
86
*/
87
function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array;
88
```
89
90
**Usage Examples:**
91
92
```typescript
93
import { bytesToHex, hexToBytes, concatBytes, utf8ToBytes } from "@noble/curves/utils";
94
95
// Hex conversion
96
const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
97
const hex = bytesToHex(bytes); // "48656c6c6f"
98
const backToBytes = hexToBytes(hex); // Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f])
99
100
// Concatenation
101
const part1 = utf8ToBytes("Hello");
102
const part2 = utf8ToBytes(" World");
103
const combined = concatBytes(part1, part2); // "Hello World" in bytes
104
```
105
106
### Number Conversion
107
108
Functions for converting between numbers and byte representations in different endianness.
109
110
```typescript { .api }
111
import {
112
bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE,
113
numberToVarBytesBE, numberToHexUnpadded, hexToNumber
114
} from "@noble/curves/utils";
115
116
/**
117
* Converts byte array to big-endian number
118
* @param bytes - Byte array to convert
119
* @returns BigInt representation
120
*/
121
function bytesToNumberBE(bytes: Uint8Array): bigint;
122
123
/**
124
* Converts byte array to little-endian number
125
* @param bytes - Byte array to convert
126
* @returns BigInt representation
127
*/
128
function bytesToNumberLE(bytes: Uint8Array): bigint;
129
130
/**
131
* Converts number to big-endian byte array with fixed length
132
* @param n - Number to convert
133
* @param len - Target byte array length
134
* @returns Big-endian byte array
135
*/
136
function numberToBytesBE(n: number | bigint, len: number): Uint8Array;
137
138
/**
139
* Converts number to little-endian byte array with fixed length
140
* @param n - Number to convert
141
* @param len - Target byte array length
142
* @returns Little-endian byte array
143
*/
144
function numberToBytesLE(n: number | bigint, len: number): Uint8Array;
145
146
/**
147
* Converts number to big-endian byte array with minimal length
148
* @param n - Number to convert
149
* @returns Big-endian byte array without leading zeros
150
*/
151
function numberToVarBytesBE(n: number | bigint): Uint8Array;
152
153
/**
154
* Converts number to hexadecimal string without padding
155
* @param num - Number to convert
156
* @returns Hex string without leading zeros or 0x prefix
157
*/
158
function numberToHexUnpadded(num: number | bigint): string;
159
160
/**
161
* Converts hexadecimal string to number
162
* @param hex - Hex string (with or without 0x prefix)
163
* @returns BigInt representation
164
*/
165
function hexToNumber(hex: string): bigint;
166
```
167
168
**Usage Examples:**
169
170
```typescript
171
import { numberToBytesBE, bytesToNumberBE, numberToHexUnpadded } from "@noble/curves/utils";
172
173
// Number to bytes conversion
174
const num = 0x12345678n;
175
const bytes = numberToBytesBE(num, 8); // 8-byte big-endian representation
176
const backToNum = bytesToNumberBE(bytes); // 0x12345678n
177
178
// Hex conversion
179
const hex = numberToHexUnpadded(255); // "ff"
180
```
181
182
### Validation and Range Checking
183
184
Functions for validating inputs and checking numeric ranges.
185
186
```typescript { .api }
187
import {
188
inRange, aInRange, abool, abytes, anumber, validateObject, isHash
189
} from "@noble/curves/utils";
190
191
/**
192
* Checks if number is within specified range
193
* @param n - Number to check
194
* @param min - Minimum value (inclusive)
195
* @param max - Maximum value (exclusive)
196
* @returns True if n is in range [min, max)
197
*/
198
function inRange(n: bigint, min: bigint, max: bigint): boolean;
199
200
/**
201
* Asserts that number is within specified range
202
* @param title - Description for error message
203
* @param n - Number to check
204
* @param min - Minimum value (inclusive)
205
* @param max - Maximum value (exclusive)
206
* @throws Error if n is not in range
207
*/
208
function aInRange(title: string, n: bigint, min: bigint, max: bigint): void;
209
210
/**
211
* Asserts that value is a boolean
212
* @param title - Description for error message
213
* @param value - Value to check
214
* @throws Error if value is not boolean
215
*/
216
function abool(title: string, value: boolean): void;
217
218
/**
219
* Asserts that value is a Uint8Array
220
* @param title - Description for error message
221
* @param value - Value to check
222
* @param length - Optional expected length
223
* @throws Error if value is not Uint8Array or wrong length
224
*/
225
function abytes(title: string, value: Uint8Array, length?: number): void;
226
227
/**
228
* Asserts that value is a number
229
* @param title - Description for error message
230
* @param value - Value to check
231
* @throws Error if value is not a number
232
*/
233
function anumber(title: string, value: number): void;
234
235
/**
236
* Validates object structure using schema
237
* @param obj - Object to validate
238
* @param validators - Schema of validation functions
239
* @param optValidators - Optional field validators
240
* @returns Validated object
241
*/
242
function validateObject<T extends Record<string, any>>(
243
obj: any,
244
validators: Record<string, (v: any) => any>,
245
optValidators?: Record<string, (v: any) => any>
246
): T;
247
248
/**
249
* Checks if value implements hash function interface
250
* @param val - Value to check
251
* @returns True if value has hash function properties
252
*/
253
function isHash(val: any): val is CHash;
254
```
255
256
### Bit Operations
257
258
Functions for bitwise operations on BigInt values.
259
260
```typescript { .api }
261
import { bitLen, bitGet, bitSet, bitMask } from "@noble/curves/utils";
262
263
/**
264
* Gets bit length of a number
265
* @param n - Number to measure
266
* @returns Number of bits needed to represent n
267
*/
268
function bitLen(n: bigint): number;
269
270
/**
271
* Gets bit value at specific position
272
* @param n - Number to read from
273
* @param pos - Bit position (0 = least significant)
274
* @returns Bit value (0n or 1n)
275
*/
276
function bitGet(n: bigint, pos: number): bigint;
277
278
/**
279
* Sets bit value at specific position
280
* @param n - Number to modify
281
* @param pos - Bit position (0 = least significant)
282
* @param value - Bit value to set
283
* @returns Modified number
284
*/
285
function bitSet(n: bigint, pos: number, value: boolean): bigint;
286
287
/**
288
* Creates bit mask with n bits set
289
* @param n - Number of bits to set
290
* @returns Bitmask with n least significant bits set
291
*/
292
function bitMask(n: number): bigint;
293
```
294
295
### Random Number Generation
296
297
Cryptographically secure random number generation.
298
299
```typescript { .api }
300
import { randomBytes } from "@noble/curves/utils";
301
302
/**
303
* Generates cryptographically secure random bytes
304
* @param bytesLength - Number of bytes to generate (default: 32)
305
* @returns Random byte array
306
*/
307
function randomBytes(bytesLength?: number): Uint8Array;
308
```
309
310
### HMAC-DRBG
311
312
Deterministic random bit generation using HMAC.
313
314
```typescript { .api }
315
import { createHmacDrbg } from "@noble/curves/utils";
316
317
/**
318
* Creates HMAC-based deterministic random bit generator
319
* @param hashLen - Hash function output length
320
* @param qByteLen - Output byte length
321
* @param hmacFn - HMAC function
322
* @returns DRBG function
323
*/
324
function createHmacDrbg<T>(
325
hashLen: number,
326
qByteLen: number,
327
hmacFn: HmacFnSync
328
): (seed: Uint8Array, k?: Uint8Array, v?: Uint8Array) => () => T;
329
```
330
331
### Utility Functions
332
333
Additional utility functions for memoization and error handling.
334
335
```typescript { .api }
336
import { memoized, notImplemented } from "@noble/curves/utils";
337
338
/**
339
* Creates memoized version of a function
340
* @param fn - Function to memoize
341
* @returns Memoized function that caches results
342
*/
343
function memoized<T extends object, R, O extends any[]>(
344
fn: (obj: T, ...args: O) => R
345
): (obj: T, ...args: O) => R;
346
347
/**
348
* Throws "not implemented" error
349
* @throws Error indicating feature is not implemented
350
*/
351
function notImplemented(): never;
352
```
353
354
### Curve-Specific Utilities
355
356
Utilities from the main utils module for curve operations.
357
358
```typescript { .api }
359
import {
360
randomBytes, ensureBytes, numberToBytesLE, bytesToNumberLE
361
} from "@noble/curves/utils";
362
363
// Re-exported from main utils - same functionality as abstract/utils
364
// but may have optimizations for specific curve implementations
365
```
366
367
### Abstract Utilities
368
369
Utilities specifically designed for abstract curve implementations, providing the same core functionality as main utils but optimized for generic curve operations.
370
371
```typescript { .api }
372
import {
373
bytesToHex, hexToBytes, bytesToNumberBE, numberToBytesBE,
374
randomBytes, ensureBytes
375
} from "@noble/curves/abstract/utils";
376
377
// Same API as main utils module
378
// These are the core utilities used internally by abstract curve implementations
379
```
380
381
### Short Weierstrass Utilities
382
383
Specialized utilities for short Weierstrass curve implementations, providing hash configuration and curve creation helpers.
384
385
```typescript { .api }
386
import { getHash, createCurve } from "@noble/curves/_shortw_utils";
387
388
/**
389
* Gets hash configuration for curve implementations
390
* @param hash - Hash function to wrap
391
* @returns Hash configuration object
392
*/
393
function getHash(hash: CHash): { hash: CHash };
394
395
/**
396
* Creates curve implementation with hash function (deprecated)
397
* @param curveDef - Curve definition parameters
398
* @param defHash - Default hash function
399
* @returns Curve function with create method
400
* @deprecated Use weierstrass() from abstract/weierstrass instead
401
*/
402
function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate;
403
404
// Type definitions
405
type CurveDef = Readonly<Omit<CurveType, 'hash'>>;
406
type CurveFnWithCreate = CurveFn & {
407
create: (hash: CHash) => CurveFn;
408
};
409
```
410
411
## Core Types
412
413
```typescript { .api }
414
// Input types
415
type Hex = Uint8Array | string; // Flexible hex input
416
type PrivKey = Hex | bigint; // Private key input
417
418
// Hash function interfaces
419
interface CHash {
420
(message: Uint8Array): Uint8Array;
421
blockLen: number; // Hash block size in bytes
422
outputLen: number; // Hash output size in bytes
423
create(): any; // Hash instance creator
424
}
425
426
interface FHash {
427
(message: Uint8Array | string): Uint8Array;
428
}
429
430
// HMAC function type
431
type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;
432
```
433
434
## Usage Patterns
435
436
### Safe Input Handling
437
438
```typescript
439
import { ensureBytes, hexToBytes, utf8ToBytes } from "@noble/curves/utils";
440
441
// Handle flexible input types
442
function processInput(input: Hex): Uint8Array {
443
return typeof input === 'string'
444
? hexToBytes(input)
445
: ensureBytes('input', input);
446
}
447
448
// Validate byte lengths
449
const key = ensureBytes('private key', userInput, 32); // Ensure 32 bytes
450
```
451
452
### Number Format Conversions
453
454
```typescript
455
import {
456
numberToBytesBE, bytesToNumberBE,
457
numberToHexUnpadded, hexToNumber
458
} from "@noble/curves/utils";
459
460
// Convert between formats
461
const num = 0x1234567890abcdefn;
462
const bytes = numberToBytesBE(num, 8); // 8-byte big-endian
463
const hex = numberToHexUnpadded(num); // "1234567890abcdef"
464
const backToNum = hexToNumber(hex); // 0x1234567890abcdefn
465
```
466
467
### Secure Comparisons
468
469
```typescript
470
import { equalBytes } from "@noble/curves/utils";
471
472
// Constant-time comparison
473
const hash1 = new Uint8Array([1, 2, 3, 4]);
474
const hash2 = new Uint8Array([1, 2, 3, 4]);
475
const isEqual = equalBytes(hash1, hash2); // true, computed in constant time
476
```