通过以太坊账户地址恢复私钥,并通过私钥恢复出对应公钥

首先通过MetaMask导出私钥
通过以太坊账户地址恢复私钥,并通过私钥恢复出对应公钥_第1张图片
然后在linux环境下中安装工具包(提前准备好nodejs环境)

npm install ethereumjs-wallet --save
npm install ethereumjs-util --save

然后新建test.js代码:

var Wallet = require('ethereumjs-wallet');
var EthUtil = require('ethereumjs-util');
// Get a wallet instance from a private key
const privateKeyBuffer = EthUtil.toBuffer('0x74995944E0A378FF9C585D0533F96338053EFEC8A84CC79DDC0AAE8CA79D7E26');
const wallet = Wallet.fromPrivateKey(privateKeyBuffer);
// Get public key
const publicKey = wallet.getPublicKeyString();
console.log(publicKey);

这部分代码参考 [link]https://medium.com/@piyopiyo/how-to-get-ethereum-public-key-from-private-key-javascript-835c276e39bc

node test.js
0x6eccc1918ddc2f4b897f7ae9b46177fd6254a29c91fa7c2c0f1ae43ccab17bf2ad18b02c032aa0acf15bf42ff675051be1f2b6f015b0444190e98f4a2119fbae

然后通过web3.js或Solidity或其他方式计算公钥的sha3-256值,即以太坊的keccak256如:

web3.eth.utils.keccak256('0x6eccc1918ddc2f4b897f7ae9b46177fd6254a29c91fa7c2c0f1ae43ccab17bf2ad18b02c032aa0acf15bf42ff675051be1f2b6f015b0444190e98f4a2119fbae')
0xc1163386715448fbf08bc5a05b444f5ca0d97a3218c354910c46566db854192f

输出的即为地址对应公钥,公钥的后20字节即为地址,可以从上面的MetaMask图中验证

你可能感兴趣的:(以太坊,公私钥,区块链)