问题描述
我想使用这个库 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());
});
});