1 创建助记词
创建助记词我们需要用到bip39
:
$ npm i bip39
// 引入 bip39
import * as bip39 from 'bip39';
// 生成助记词
const mnemonic = bip39.generateMnemonic();
console.log('Generated mnemonic:', mnemonic);
// panda during find cart hedgehog spend pony recall plunge scatter sentence tape
2 根据助记词生成密钥对
这一步我们需要用到ethereumjs-wallet
:
$ npm i ethereumjs-wallet
import { hdkey } from 'ethereumjs-wallet';
let seed = bip39.mnemonicToSeed(mnemonic);
let hdWallet = hdkey.fromMasterSeed(seed);
let keypair = hdWallet.derivePath("m/44'/60'/0'/0/0");
console.log(keypair);
3 获取账户地址
// 获取钱包
const wallet = keypair.getWallet();
console.log(wallet);
// 获取账户地址
const address = wallet.getAddressString();
console.log(address);
// 0x6858dc3a3e1c2f4de7da740bb0257ed8a0ae582b
const checkAddress = wallet.getChecksumAddressString();
console.log(checkAddress);
// 0x6858DC3A3E1c2F4de7dA740bb0257ED8A0aE582b
4 获取私钥
// 获取私钥
const privateKeyString = wallet.getPrivateKeyString();
console.log(privateKeyString);
// 0x67b50b90ea53409a8df8f6d025b8d90d1ba10e9d9fe704bb255aed85691589d2
5 导出至keystore
// 导出至keystore
// 1. web3.js
import { Web3 } from 'web3';
const web3 = new Web3('https://sepolia.infura.io/v3/YOUR_INFURA_ID')
const keystore = web3.eth.accounts.encrypt(privateKeyString,'111111');
console.log(keystore);
// 2. wallet对象
const v3String = await wallet.toV3('111111');
console.log(JSON.stringify(v3String));
6 从keystore导入私钥
// web3.js
const privateKeyString1 = web3.eth.accounts.decrypt(keystore,'111111');
console.log(privateKeyString1)
// wallet
import ethwalletfrom 'ethereumjs-wallet';
const privateKeyString2 = await ethwallet.fromV3(v3String,'111111')
console.log(JSON.stringify(privateKeyString2));
声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)进行许可,使用时请注明出处。
Author: mengbin
blog: mengbin
Github: mengbin92
cnblogs: 恋水无意
腾讯云开发者社区:孟斯特