Skip to content

Keystore

Utilities & types for working with Keystores.

Examples

Below are some examples demonstrating common usages of the Keystore module:

Encrypting Private Keys

Private keys can be encrypted into a JSON keystore using Keystore.encrypt:

import { Keystore, Secp256k1 } from 'ox'
 
// Generate a random private key.
const privateKey = Secp256k1.randomPrivateKey()
 
// Derive a key from a password.
const [key, opts] = Keystore.pbkdf2({ password: 'testpassword' })
 
// Encrypt the private key.
const keystore = Keystore.encrypt(privateKey, key, opts)
{
"crypto": {
"cipher": "aes-128-ctr",
"ciphertext": "...",
"cipherparams": {
"iv": "...",
},
"kdf": "pbkdf2",
"kdfparams": {
"salt": "...",
"dklen": 32,
"prf": "hmac-sha256",
"c": 262144,
},
"mac": "...",
},
"id": "...",
"version": 3,
}

Decrypting Private Keys

Private keys can be decrypted from a JSON keystore using Keystore.decrypt:

import { Keystore, Secp256k1 } from 'ox'
 
const keystore = { crypto: { ... }, id: '...', version: 3 }
 
// Derive the key.
const key = Keystore.toKey(keystore, { password: 'testpassword' })
 
// Decrypt the private key.
const decrypted = Keystore.decrypt(keystore, key)
"0x..."

Functions

NameDescription
Keystore.decryptDecrypts a JSON keystore into a private key.
Keystore.encryptEncrypts a private key as a JSON keystore using a derived key.
Keystore.pbkdf2Derives a key from a password using PBKDF2.
Keystore.pbkdf2AsyncDerives a key from a password using PBKDF2.
Keystore.scryptDerives a key from a password using scrypt.
Keystore.scryptAsyncDerives a key from a password using scrypt.
Keystore.toKeyExtracts a Key from a JSON Keystore to use for decryption.
Keystore.toKeyAsyncExtracts a Key asynchronously from a JSON Keystore to use for decryption.

Types

NameDescription
Keystore.DeriveOptsDerivation Options.
Keystore.KeyKey.
Keystore.KeystoreKeystore.
Keystore.Pbkdf2DeriveOptsPBKDF2 Derivation Options.
Keystore.ScryptDeriveOptsScrypt Derivation Options.