Web3 by Example: Keystores

Keystore is a JSON-encoded file that contains a single (randomly generated) private key, encrypted by a passphrase for extra security.

Create a random wallet.

Encrypt the wallet using password, this will return a JSON-encoded string. We can store it in a file.

We can also recover the wallet from the keystore by decrypting an encrypted JSON wallet.

keystore.js

const { ethers } = require("ethers");
(async () => {
const wallet = ethers.Wallet.createRandom();
const keystoreJson = await wallet.encrypt("password");
console.log("keystoreJson", keystoreJson);
const w = await ethers.Wallet.fromEncryptedJson(keystoreJson, "password");
console.log("address", w.address);
})();

output

➜ node keystore.js
keystoreJson {"address":"0bd9b4303ea0124585327eeadefa16515d5d190d","id":"2513bdcd-546b-4160-a818-730683cf695e","version":3,"Crypto":{"cipher":"aes-128-ctr","cipherparams":{"iv":"23c6da59b9a4795d7b53cc0863b66ef6"},"ciphertext":"557dbc0e6c667335db43407a34451e0397d3fd3deb4857c233b1ec8714731c7a","kdf":"scrypt","kdfparams":{"salt":"deb00631ee308c91ccea4c83d795ac762ea923d10481f4d85d1631f87d791635","n":131072,"dklen":32,"p":1,"r":8},"mac":"98b2dd72b906c8c0290348411b3be3f22996d589d0c510e1cf8424fb6592c19f"},"x-ethers":{"client":"ethers.js","gethFilename":"UTC--2022-02-27T07-28-24.0Z--0bd9b4303ea0124585327eeadefa16515d5d190d","mnemonicCounter":"7c3b8c746320c04752c5d0b723b16cb3","mnemonicCiphertext":"1c6ab6d2ca4b0609e4be80e0e0bda3bb","path":"m/44'/60'/0'/0/0","locale":"en","version":"0.1"}}
address 0x0bd9B4303ea0124585327EEAdefA16515d5D190d

Next example: HD Wallet