Ether.js

How do I encrypt and decrypt a wallet in Ethersjs


What is Wallet Encryption?

Wallet encryption is the process of securing a wallet's private key with a password. This ensures that even if someone gains access to the wallet file, they cannot use it without the password.

Ethers.js provides a simple way to encrypt and decrypt wallets using the encrypt and fromEncryptedJson methods.

Encrypting a Wallet

To encrypt a wallet, you need to have a wallet instance. You can create a wallet using a private key or a mnemonic phrase. Once you have the wallet, you can encrypt it with a password.

Sample Code for Encrypting a Wallet

const { ethers } = require(`ethers`);
// Create a wallet from a random private key
const wallet = ethers.Wallet.createRandom();
// Define a password for encryption
const password = `your_secure_password`;
// Encrypt the wallet
async function encryptWallet() {
    const encryptedJson = await wallet.encrypt(password);
    console.log(`Encrypted Wallet JSON:`, encryptedJson);
}
encryptWallet();

Decrypting a Wallet

To decrypt a wallet, you need the encrypted JSON string and the password used for encryption. The fromEncryptedJson method will return a wallet instance if the password is correct.

Sample Code for Decrypting a Wallet

const encryptedJson = `your_encrypted_wallet_json_here`; // Replace with your encrypted JSON
const password = `your_secure_password`; // The same password used for encryption
async function decryptWallet() {
    try {
        const wallet = await ethers.Wallet.fromEncryptedJson(encryptedJson, password);
        console.log(`Decrypted Wallet Address:`, wallet.address);
    } catch (error) {
        console.error(`Error decrypting wallet:`, error);
    }
}
decryptWallet();

How It Works

- The encrypt method takes a password and returns an encrypted JSON string representing the wallet.
- The fromEncryptedJson method takes the encrypted JSON and the password to return the original wallet instance.
- If the password is incorrect, an error will be thrown during decryption.

Conclusion

You have successfully learned how to encrypt and decrypt a wallet using Ethers.js! Always ensure that your password is strong and kept secure, as it is the key to accessing your wallet.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.