Icon HelpCircleForumIcon Link

⌘K

Icon HelpCircleForumIcon Link
Encrypting and Decrypting

Icon LinkEncrypting and Decrypting

JSON wallets are a standardized way of storing wallets securely. They follow a specific schema and are encrypted using a password. This makes it easier to manage multiple wallets and securely store them on disk. This guide will take you through the process of encrypting and decrypting JSON wallets using the Typescript SDK.

Icon LinkEncrypting a Wallet

We will be calling encrypt from the WalletUnlocked instance which will take a password as the argument. It will encrypt the private key using a cipher and returns the JSON keystore wallet. You can then securely store this JSON wallet.

Here is an example of how you can accomplish this:

// #import { Wallet, fs };
 
const wallet = Wallet.generate({
  provider,
});
 
const password = 'my-password';
 
const jsonWallet = await wallet.encrypt(password);
 
fs.writeFileSync('secure-path/my-wallet.json', jsonWallet);

Please note that encrypt must be called within an instance of WalletUnlocked . This instance can only be achieved through passing a private key or mnemonic phrase to a locked wallet.

Icon LinkDecrypting a Wallet

To decrypt the JSON wallet and retrieve your private key, you can call fromEncryptedJson on a Wallet instance. It takes the encrypted JSON wallet and the password as its arguments, and returns the decrypted wallet.

Here is an example:

// #import { Wallet, fs };
 
const jsonWallet = fs.readFileSync('secure-path/my-wallet.json', 'utf-8');
 
const password = 'my-password';
 
const decryptedWallet = await Wallet.fromEncryptedJson(jsonWallet, password, provider);
 
const myBalance = await decryptedWallet.getBalance();

In this example, decryptedWallet is an instance of WalletUnlocked class, now available for use.

Icon LinkImportant

Remember to securely store your encrypted JSON wallet and password. If you lose them, there will be no way to recover your wallet. For security reasons, avoid sharing your private key, encrypted JSON wallet or password with anyone.