0

I want to encrypt and decrypt the message based on ECIES using this library JavaScript Elliptic curve cryptography library. I want to import my private key and get the public key from it because I do not have a new private key generated each time I run the code.

The code:

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());
  });
});

However, the code is not working and shows this error:

    throw new Error(message || "Assertion failed");
    ^
    Error: Bad private key
ismsm
  • 143
  • 2
  • 11

1 Answers1

1

eccrypto.getPublic() expects a Buffer as argument, not a string. Try this instead:

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());
  });
});
D. Pardal
  • 6,173
  • 1
  • 17
  • 37