A collection of useful crypto utilities for Polkadot ecosystem projects
npx @tessl/cli install tessl/npm-polkadot--util-crypto@13.5.00
# @polkadot/util-crypto
1
2
@polkadot/util-crypto is a comprehensive cryptographic utilities library designed specifically for the Polkadot ecosystem. It provides a wide range of cryptographic functions including key management, digital signatures, hashing algorithms, address encoding/decoding, and hierarchical deterministic key derivation across multiple cryptographic schemes.
3
4
## Package Information
5
6
- **Package Name**: @polkadot/util-crypto
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @polkadot/util-crypto`
10
11
## Core Imports
12
13
```typescript
14
import {
15
cryptoWaitReady,
16
mnemonicGenerate,
17
encodeAddress,
18
decodeAddress,
19
sr25519PairFromSeed,
20
ed25519Sign
21
} from "@polkadot/util-crypto";
22
```
23
24
For CommonJS:
25
26
```javascript
27
const {
28
cryptoWaitReady,
29
mnemonicGenerate,
30
encodeAddress,
31
decodeAddress,
32
sr25519PairFromSeed,
33
ed25519Sign
34
} = require("@polkadot/util-crypto");
35
```
36
37
## Basic Usage
38
39
```typescript
40
import {
41
cryptoWaitReady,
42
mnemonicGenerate,
43
mnemonicValidate,
44
mnemonicToMiniSecret,
45
sr25519PairFromSeed,
46
encodeAddress,
47
signatureVerify
48
} from "@polkadot/util-crypto";
49
50
// Initialize crypto before usage
51
await cryptoWaitReady();
52
53
// Generate and validate mnemonic
54
const mnemonic = mnemonicGenerate();
55
const isValid = mnemonicValidate(mnemonic);
56
57
// Create key pair from mnemonic
58
const seed = mnemonicToMiniSecret(mnemonic);
59
const pair = sr25519PairFromSeed(seed);
60
61
// Encode address with Polkadot prefix (0)
62
const address = encodeAddress(pair.publicKey, 0);
63
64
// Sign and verify message
65
const message = new TextEncoder().encode("Hello Polkadot");
66
const signature = sr25519Sign(message, pair);
67
const verified = signatureVerify(message, signature, address);
68
```
69
70
## Architecture
71
72
@polkadot/util-crypto is organized around several key functional areas:
73
74
- **Address System**: SS58 address encoding/decoding with multi-network support
75
- **Cryptographic Schemes**: Support for sr25519, ed25519, secp256k1, and ECDSA
76
- **Key Management**: Hierarchical deterministic key derivation and mnemonic handling
77
- **Hashing Algorithms**: Blake2, Keccak, SHA, and xxHash implementations
78
- **Encoding Utilities**: Base32, Base58, and Base64 encoding/decoding
79
- **Security Features**: Password-based key derivation, encryption, and digital signatures
80
81
## Capabilities
82
83
### Crypto Initialization
84
85
Core initialization functions to prepare the WebAssembly crypto backend.
86
87
```typescript { .api }
88
function cryptoWaitReady(): Promise<boolean>;
89
function cryptoIsReady(): boolean;
90
```
91
92
[Crypto Initialization](./crypto-init.md)
93
94
### Address Management
95
96
SS58 address encoding, decoding, and validation with support for multi-signature and derived addresses.
97
98
```typescript { .api }
99
function encodeAddress(publicKey: Uint8Array, prefix?: number): string;
100
function decodeAddress(address: string, ignoreChecksum?: boolean, prefix?: number): Uint8Array;
101
function checkAddress(address: string, prefix?: number): [boolean, string | null];
102
function addressEq(a: string, b: string): boolean;
103
```
104
105
[Address Management](./address.md)
106
107
### Key Pair Generation
108
109
Key pair generation and management for sr25519, ed25519, and secp256k1 cryptographic schemes.
110
111
```typescript { .api }
112
interface Keypair {
113
publicKey: Uint8Array;
114
secretKey: Uint8Array;
115
}
116
117
interface Seedpair {
118
publicKey: Uint8Array;
119
seed: Uint8Array;
120
}
121
122
type KeypairType = 'ed25519' | 'sr25519' | 'ecdsa' | 'ethereum';
123
124
function sr25519PairFromSeed(seed: Uint8Array): Keypair;
125
function ed25519PairFromSeed(seed: Uint8Array): Keypair;
126
function secp256k1PairFromSeed(seed: Uint8Array): Keypair;
127
```
128
129
[Key Pair Generation](./keypairs.md)
130
131
### Digital Signatures
132
133
Signing and verification functions for multiple cryptographic schemes with signature format detection.
134
135
```typescript { .api }
136
interface VerifyResult {
137
crypto: 'none' | KeypairType;
138
isValid: boolean;
139
isWrapped: boolean;
140
publicKey: Uint8Array;
141
}
142
143
function sr25519Sign(message: string | Uint8Array, keypair: Partial<Keypair>): Uint8Array;
144
function ed25519Sign(publicKey: Uint8Array, secretKey: Uint8Array, message: Uint8Array): Uint8Array;
145
function signatureVerify(message: Uint8Array, signature: Uint8Array, addressOrPublicKey: string | Uint8Array): VerifyResult;
146
```
147
148
[Digital Signatures](./signatures.md)
149
150
### Mnemonic Management
151
152
BIP39-compatible mnemonic generation, validation, and seed derivation.
153
154
```typescript { .api }
155
function mnemonicGenerate(numWords?: 12 | 15 | 18 | 21 | 24, wordlist?: string[]): string;
156
function mnemonicValidate(mnemonic: string, wordlist?: string[]): boolean;
157
function mnemonicToMiniSecret(mnemonic: string, password?: string): Uint8Array;
158
function mnemonicToEntropy(mnemonic: string, wordlist?: string[]): Uint8Array;
159
```
160
161
[Mnemonic Management](./mnemonic.md)
162
163
### Hierarchical Key Derivation
164
165
Hierarchical deterministic key derivation supporting both hard and soft derivation paths.
166
167
```typescript { .api }
168
function keyFromPath(pair: Keypair, path: string, type: KeypairType): Keypair;
169
function keyExtractPath(path: string): { path: string; password?: string };
170
function hdEthereum(seed: Uint8Array, path?: string): Keypair;
171
function hdLedger(mnemonic: string, path: string, rounds?: number): Keypair;
172
```
173
174
[Hierarchical Key Derivation](./key-derivation.md)
175
176
### Hashing Algorithms
177
178
Comprehensive hashing functions including Blake2, Keccak, SHA, and xxHash.
179
180
```typescript { .api }
181
function blake2AsU8a(data: Uint8Array, bitLength?: 64 | 128 | 256 | 512, key?: Uint8Array): Uint8Array;
182
function keccakAsU8a(value: Uint8Array, bitLength?: 256 | 512): Uint8Array;
183
function sha256AsU8a(value: Uint8Array): Uint8Array;
184
function xxhashAsU8a(data: Uint8Array, bitLength?: 64 | 128 | 256): Uint8Array;
185
```
186
187
[Hashing Algorithms](./hashing.md)
188
189
### Base Encoding
190
191
Encoding and decoding utilities for Base32, Base58, and Base64 formats.
192
193
```typescript { .api }
194
function base58Encode(value: Uint8Array, ipfsCompat?: boolean): string;
195
function base58Decode(value: string, ipfsCompat?: boolean): Uint8Array;
196
function base64Encode(value: Uint8Array): string;
197
function base64Decode(value: string): Uint8Array;
198
```
199
200
[Base Encoding](./base-encoding.md)
201
202
### Password-Based Key Derivation
203
204
PBKDF2 and Scrypt implementations for password-based key derivation.
205
206
```typescript { .api }
207
function pbkdf2Encode(passphrase: string, salt?: Uint8Array, rounds?: number, length?: number): Uint8Array;
208
function scryptEncode(passphrase: string, salt?: Uint8Array, N?: number, r?: number, p?: number, dkLen?: number): Uint8Array;
209
```
210
211
[Password-Based Key Derivation](./key-derivation-pbkdf.md)
212
213
### JSON Encryption
214
215
Secure JSON encryption and decryption with password protection.
216
217
```typescript { .api }
218
interface EncryptedJson {
219
encoded: string;
220
encoding: EncryptedJsonDescriptor;
221
}
222
223
interface EncryptedJsonDescriptor {
224
content: string[];
225
type: EncryptedJsonEncoding | EncryptedJsonEncoding[];
226
version: EncryptedJsonVersion;
227
}
228
229
function jsonEncrypt(data: Uint8Array, contentType: string[], passphrase: string): EncryptedJson;
230
function jsonDecrypt(json: EncryptedJson, passphrase: string): Uint8Array;
231
```
232
233
[JSON Encryption](./json-encryption.md)
234
235
### Random Number Generation
236
237
Cryptographically secure random number generation in various formats.
238
239
```typescript { .api }
240
function randomAsU8a(bitLength?: number): Uint8Array;
241
function randomAsHex(bitLength?: number): string;
242
function randomAsNumber(bitLength?: number): number;
243
```
244
245
[Random Number Generation](./random.md)
246
247
### Ethereum Compatibility
248
249
Ethereum address handling and compatibility utilities.
250
251
```typescript { .api }
252
function ethereumEncode(addressOrPublic: string | Uint8Array): string;
253
function isEthereumAddress(address: string): boolean;
254
function addressToEvm(address: string): Uint8Array;
255
function evmToAddress(evmAddress: Uint8Array, prefix?: number, hashType?: 'blake2' | 'keccak'): string;
256
```
257
258
[Ethereum Compatibility](./ethereum.md)
259
260
### NaCl Secret-key Encryption
261
262
NaCl secretbox encryption and decryption for authenticated symmetric encryption.
263
264
```typescript { .api }
265
interface NaclEncrypted {
266
encrypted: Uint8Array;
267
nonce: Uint8Array;
268
}
269
270
function naclEncrypt(message: Uint8Array, secret: Uint8Array, nonce?: Uint8Array): NaclEncrypted;
271
function naclDecrypt(encrypted: Uint8Array, nonce: Uint8Array, secret: Uint8Array): Uint8Array | null;
272
```
273
274
### Network Constants
275
276
Network configuration constants for multi-chain support across Polkadot ecosystem.
277
278
```typescript { .api }
279
const allNetworks: Network[];
280
const availableNetworks: Network[];
281
const selectableNetworks: Network[];
282
```
283
284
## Core Types
285
286
```typescript { .api }
287
interface Keypair {
288
/** The publicKey for this pair */
289
publicKey: Uint8Array;
290
/** The secretKey for this pair */
291
secretKey: Uint8Array;
292
}
293
294
interface Seedpair {
295
/** The publicKey for this pair */
296
publicKey: Uint8Array;
297
/** The seed used to construct the pair */
298
seed: Uint8Array;
299
}
300
301
/** The supported types of pairs */
302
type KeypairType = 'ed25519' | 'sr25519' | 'ecdsa' | 'ethereum';
303
304
interface VerifyResult {
305
/** The detected crypto interface, or 'none' if not detected */
306
crypto: 'none' | KeypairType;
307
/** The validity for this result, false if invalid */
308
isValid: boolean;
309
/** Flag to indicate if the passed data was wrapped in <Bytes>...</Bytes> */
310
isWrapped: boolean;
311
/** The extracted publicKey */
312
publicKey: Uint8Array;
313
}
314
315
interface DeriveJunction {
316
/** Chain code for derivation */
317
readonly chainCode: Uint8Array;
318
/** Whether this is a hard derivation */
319
readonly isHard: boolean;
320
/** Whether this is a soft derivation */
321
readonly isSoft: boolean;
322
}
323
324
interface ExtractResult {
325
derivePath: string;
326
password?: string;
327
path: DeriveJunction[];
328
phrase: string;
329
}
330
331
interface NaclEncrypted {
332
encrypted: Uint8Array;
333
nonce: Uint8Array;
334
}
335
336
type EncryptedJsonVersion = '0' | '1' | '2' | '3';
337
type EncryptedJsonEncoding = 'none' | 'scrypt' | 'xsalsa20-poly1305';
338
type Prefix = number;
339
```