Signing and verifying messages with PrivateKey

Is there a good alternative in the new version of Bitcore for signing a message with a PrivateKey and verifying with the corresponding PublicKey?

I was using bitcore.Message.signMessage and bitcore.Message.verifyWithPubKey in v0.1.41, but I am trying to upgrade to the newest version. There does not seem to be an equivalent Message. I tried using the bitcore.crypto.ECDSA without success, and I could not find any documentation for it.

Thanks for any help!

This should go part of the way there:

'use strict';

var bitcore = require('bitcore');
var PrivateKey = bitcore.PrivateKey;
var PublicKey = bitcore.PublicKey;
var BufferWriter = bitcore.encoding.BufferWriter;
var ECDSA = bitcore.crypto.ECDSA;
var sha256sha256 = bitcore.crypto.Hash.sha256sha256;

var Message = function() {};

Message.sign = function(message, privateKey) {
  var hash = Message.magicHash(message);
  var ecdsa = new ECDSA();
  ecdsa.hashbuf = hash;
  ecdsa.privkey = privateKey;
  ecdsa.pubkey = privateKey.toPublicKey();
  ecdsa.signRandomK();
  ecdsa.calci();
  return ecdsa.sig;
};

Message.verify = function(message, publicKey, signature) {
  var hash = Message.magicHash(message);
  var verified = ECDSA.verify(hash, signature, publicKey);
  return verified;
};

Message.magicBytes = new Buffer('Bitcoin Signed Message:\n');

Message.magicHash = function(str) {
  var magicBytes = Message.magicBytes;
  var prefix1 = BufferWriter.varintBufNum(magicBytes.length);
  var message = new Buffer(str);
  var prefix2 = BufferWriter.varintBufNum(message.length);
  var buf = Buffer.concat([prefix1, magicBytes, prefix2, message]);
  var hash = sha256sha256(buf);
  return hash;
};

Message.sign returns an instance of Signature which has a toCompact method that returns a Buffer, and can be base64 encoded with sig.toCompact().toString('base64'); Likewise an instance of Signature can be created for verification with Signature.fromCompact(new Buffer('stringsignaturefrombitcoin-qt', 'base64'));

Thank you very much! I will be trying this tomorrow. Was message signing obscure enough to be removed from the library? Perhaps it could at least exist as a subproject such as “bitcore-message”.

Edit: Looks like this is already planned. https://github.com/bitpay/bitcore/issues/1002

We’ll bump the bitcore-message priority given many people are wanting to use it. Thanks for your feedback!

No problem! I’ll watch for bitcore-message and contribute if I can.

Thanks again!

Should be published soon, merge request is out: https://github.com/bitpay/bitcore-message/pull/1

The API should be improved for the main use case with a base64 signed string as from Bitcoin-QT. There are methods for directly verifying with a public key, in additional to verifying with an address.

Thank you again! I’ve added bitcore-message to my project and it is working great.