抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

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-walletethereumjs-util

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// import Wallet from "ethereumjs-wallet";
// import EthUtil from "ethereumjs-util";

// 因为当前的没指定模块,所以默认使用require语句导入包
var Wallet = require('ethereumjs-wallet').default;
var EthUtil = require('ethereumjs-util');

// Get a wallet instance from a private key
// privatekey
const privateKey = '';
const privateKeyBuffer = EthUtil.toBuffer(privateKey);
const wallet = Wallet.fromPrivateKey(privateKeyBuffer);

// Get a public key
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";

// 获取本地的provider
const provider = new ethers.providers.JsonRpcProvider("HTTP://127.0.0.1:8545");

// 根据私钥生成 singer对象
const privateKey = "0x9b139483dc6f6c8782fda2301e9b65a75b3d084d79e79e04c64683bebfa1741d";
const wallet = new ethers.Wallet(privateKey,provider);

// 选择一个私钥
let testPK = privateKey;

// 计算公钥
// const publicKey = curve.keyFromPrivate(testPK).publicKey("hex");
let publicKey = wallet.publicKey;


// 0x607039d2266b689f20e030fdb0033824bcda33bce462ad2504e289f90df96381c363eb4bf5b2c080a56984bdcc8fbd6185053aec487a6fe988bfdef5eba1d55f
// 0x04607039d2266b689f20e030fdb0033824bcda33bce462ad2504e289f90df96381c363eb4bf5b2c080a56984bdcc8fbd6185053aec487a6fe988bfdef5eba1d55f


// let publicKey = "0x04607039d2266b689f20e030fdb0033824bcda33bce462ad2504e289f90df96381c363eb4bf5b2c080a56984bdcc8fbd6185053aec487a6fe988bfdef5eba1d55f";
let newKey = publicKey.substring(0,2) + publicKey.substring(4);
console.log(`newKey = ${newKey}`);

运行结果:

image-20240412164137831

运行结果:

image-20240412164214952

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上的结果:

image-20240412164148748

genache上查看钱包地址:

image-20240412164157178

参考链接1

参考链接2

评论



政策 · 统计 | 本站使用 Volantis 主题设计