首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试从私钥生成比特币公有地址失败

尝试从私钥生成比特币公有地址失败
EN

Stack Overflow用户
提问于 2019-04-02 16:07:21
回答 1查看 66关注 0票数 0

我有一个从随机生成的私钥生成比特币公共地址的程序。但是,当我在blockchain.info上测试公有地址的有效性时,它告诉我该地址无效。我在代码中哪里出错了?

代码语言:javascript
复制
//modules
const secureRandom = require("secure-random");
const elliptic = require("elliptic");
const ecdsa = new elliptic.ec('secp256k1');
const sha256 = require('js-sha256');
const ripemd160 = require('ripemd160');
const base58 = require('bs58');
//variable that caps the address possiblities due to elliptic curve limitations
const max = Buffer.from("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140","hex");
//generates a key that does not exceed 'max'
  function createWalletAddress(){
      var foundPrivateKey = false;
      var privateKey;
      while(!foundPrivateKey){
        privateKey=secureRandom.randomBuffer(32);
        if(Buffer.compare(max,privateKey)){
          foundPrivateKey=true
        }
      }
      //prints the private key generated
      console.log("Private: " +privateKey.toString("hex"))
      //turns private key into public and prints it
      var keys = ecdsa.keyFromPrivate(privateKey);
      var publicKey = keys.getPublic("hex");
      console.log("Public: "+publicKey);
      //getting the public key hash
      const hashBeforePKH = sha256(Buffer.from(publicKey, "hex"));
      const publicKeyHash = new ripemd160().update(Buffer.from(hashBeforePKH,"hex")).digest();
      console.log("PKH "+publicKeyHash.toString("hex"));
      return publicKeyHash;
  }

  function createPublicAddress(publicKeyHash){
      const addPrefix="00"+publicKeyHash.toString('hex');
      const hashAddress=sha256(addPrefix);
      const hashAgain = sha256(Buffer.from(hashAddress,"hex"));
      const checkSum = hashAgain.substring(0,8);
      const combine = addPrefix.toString("hex")+checkSum;
      const address= base58.encode(Buffer.from(combine,"hex"));
       console.log("address " + address);
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-02 22:29:20

校验和计算错误,应为0xf38580e3

尝试散列缓冲区而不是字符串:

代码语言:javascript
复制
function createPublicAddress(publicKeyHash){
  const addPrefix="00"+publicKeyHash.toString('hex');
  const hashAddress=sha256(Buffer.from(addPrefix, 'hex'));
  ...
}

你也可以使用像bs58check这样的东西来代替手动计算校验和。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55469782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档