如何用ethers.js SDK转换压缩公钥及获取钱包未压缩公钥?
用ethers.js获取/转换未压缩公钥的方法
一、创建钱包时直接获取65字节未压缩公钥
使用ethers创建钱包后,默认的publicKey属性返回33字节的压缩公钥。要直接获取未压缩格式,只需访问钱包实例的publicKeyUncompressed属性:
const { ethers } = require("ethers"); // 生成随机钱包 const wallet = ethers.Wallet.createRandom(); // 获取65字节未压缩公钥(前缀为0x04) const uncompressedPublicKey = wallet.publicKeyUncompressed; console.log("未压缩公钥:", uncompressedPublicKey);
二、将已有压缩公钥转换为未压缩公钥
如果手里已有33字节的压缩公钥(以0x02或0x03开头),可以通过ethers.PublicKey类完成转换:
const { ethers } = require("ethers"); // 替换为你的33字节压缩公钥(带0x前缀) const compressedPublicKey = "0x02abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"; // 从压缩公钥创建PublicKey实例 const publicKeyInstance = ethers.PublicKey.from(compressedPublicKey); // 获取未压缩公钥 const uncompressedPublicKey = publicKeyInstance.uncompressed; console.log("转换后的未压缩公钥:", uncompressedPublicKey);
补充说明
- 压缩公钥:以
0x02或0x03开头,共33字节(1字节前缀+32字节x坐标) - 未压缩公钥:以
0x04开头,共65字节(1字节前缀+32字节x坐标+32字节y坐标)
内容的提问来源于stack exchange,提问作者CharlesQHappy
相关产品推荐
相关产品推荐

