Exchange_Of_prikey_pubkey
Private Key <=> Public Key
1. 了解 ECDSA
算法
ECDSA链接1
ECDSA链接2
2. secp256k1曲线
比特币和以太坊使用secp256k1定义的椭圆曲线
secp256k1曲线
3. 安装库
1 2 3
| npm install ethereumjs-wallet --save 或 npm install ethereumjs-util --save
|
这两条命令任意执行一条即可
4. 从私钥获取公钥
4.1 方法一
使用 ethereumjs-wallet
和 ethereumjs-util
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
var Wallet = require('ethereumjs-wallet').default; var EthUtil = require('ethereumjs-util');
const privateKey = ''; const privateKeyBuffer = EthUtil.toBuffer(privateKey); const wallet = Wallet.fromPrivateKey(privateKeyBuffer);
const publicKey = wallet.getPublicKeyString(); console.log(`publicKey is => ${publicKey}`);
|
4.2 方法二
使用的是ethersjs
中的 Waller
钱包的publicKey属性获取钱包的公钥,但是获取公钥会在起始位置多出04
这个数据段,我暂时还不知道是什么东西
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import { ethers } from "ethers";
const provider = new ethers.providers.JsonRpcProvider("HTTP://127.0.0.1:8545");
const privateKey = "0x9b139483dc6f6c8782fda2301e9b65a75b3d084d79e79e04c64683bebfa1741d"; const wallet = new ethers.Wallet(privateKey,provider);
let testPK = privateKey;
let publicKey = wallet.publicKey;
let newKey = publicKey.substring(0,2) + publicKey.substring(4); console.log(`newKey = ${newKey}`);
|
运行结果:

运行结果:

5. 获取以太坊的钱包地址
钱包地址的计算式:
address = address(keccak256(publicKey))
solidity代码:
编译器为0.4版本的
1 2 3 4 5 6 7 8 9 10
| pragma solidity ^0.4.0;
contract publicKey { // to compute the metamask publicKey function getPublicKey1(bytes _publickey) external pure returns (address _subPublickey) { _subPublickey = address(keccak256(_publickey)); return _subPublickey; } }
|
编译器为0.8版本的
1 2 3 4 5 6 7 8 9 10 11 12
| // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract publicKey { // to compute the metamask publicKey function getPublicKey1(bytes memory _publickey) external pure returns (address _subPublickey) { _subPublickey = address(uint160(uint256(keccak256(_publickey)))); return _subPublickey; } }
|
remix上的结果:

genache上查看钱包地址:

参考链接1
参考链接2