微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

导入私钥的 JavaScript 椭圆曲线加密错误:私钥错误?

如何解决导入私钥的 JavaScript 椭圆曲线加密错误:私钥错误?

我想使用这个库 JavaScript Elliptic curve cryptography library 基于 ECIES 加密和解密消息。 我想导入我的私钥并从中获取公钥,因为每次运行代码时我都没有生成新的私钥。

代码

var eccrypto = require("eccrypto");

var privateKeyB = 'efae5b8156d785913e244c39ca5b9bee1a46875d123d2f49bbeb0a91474118cf';
var publicKeyB = eccrypto.getPublic(privateKeyB);
console.log(publicKeyB.toString('hex'))

// Encrypting the message for B.
eccrypto.encrypt(publicKeyB,Buffer.from("msg to b")).then(function(encrypted) {
  // B decrypting the message.
  eccrypto.decrypt(privateKeyB,encrypted).then(function(plaintext) {
    console.log("Message to part B:",plaintext.toString());
  });
});

但是,代码不起作用并显示错误

    throw new Error(message || "Assertion Failed");
    ^
    Error: Bad private key

解决方法

eccrypto.getPublic() 需要 Buffer 作为参数,而不是 string。试试这个:

var eccrypto = require("eccrypto");

var privateKeyB = Buffer.from('efae5b8156d785913e244c39ca5b9bee1a46875d123d2f49bbeb0a91474118cf','hex');
var publicKeyB = eccrypto.getPublic(privateKeyB);
console.log(publicKeyB.toString('hex'))

// Encrypting the message for B.
eccrypto.encrypt(publicKeyB,Buffer.from("msg to b")).then(function(encrypted) {
  // B decrypting the message.
  eccrypto.decrypt(privateKeyB,encrypted).then(function(plaintext) {
    console.log("Message to part B:",plaintext.toString());
  });
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。