Objective — By the end of this article you will be able to digitally sign messages with Bitcoin or any other blockchain’s public-private key pair. FLO blockchain is used in the example. bitcoinjs-lib and bitcoinjs-message modules of nodejs are used.

What is a digital signature?

Code

Pre-setup

At the time of writing, 13 Auguest 2018, bitcoinjs-message only works with version 3.x.x of bitcoinjs-lib.

mkdir projectDir

cd projectDir

npm init // creates packages.json file

npm install bitcoinjs-lib@3.3.2 // Install specific version

npm install bitcoinjs-message

I am also assuming you have your public and private key pair with you. Please let me know in the comments if I should make changes to the script to show how to generate public-private keys.

Main script

I am currently using FLO testnet addresses for the following script. You can use any network you wish by specifying the right address generation parameters ie. pubKeyHash, scriptHash, wif (Secret key), public and private headers. For Bitcoin and Bitcoin based blockchains these values can be found in the chainparams.cpp file.

var bitcoin = require('bitcoinjs-lib') // v3.x.x

var bitcoinMessage = require('bitcoinjs-message') // Parameters required for FLO address generation

const FLOTESTNET = {

messagePrefix: '\x19FLO testnet Signed Message:

',

bip32: {

public: 0x013440e2,

private: 0x01343c23

},

pubKeyHash: 0x73,

scriptHash: 0xc6,

wif: 0xef

} // Sign a message

// For Bitcoin network do not specify any network, its default var keyPair = bitcoin.ECPair.fromWIF('cRgnQe9MUu1JznntrLaoQpB476M8PURvXVQB5R2eqms5tXnzNsrr', FLOTESTNET)

var privateKey = keyPair.d.toBuffer(32)

var message = 'Hey this is Ranchi Mall' var signature = bitcoinMessage.sign(message, privateKey, keyPair.compressed)

console.log(signature.toString('base64'))

// => 'ILqvGGBI89K8Tk9/BgrGPSMTB9ZY+Z88Z0GjVsx7uPTwOfQ+eNj/VZKZ40iSbUPgz6mSBvo6w1Dkzns9DqfYa2o=' // Verify a message

var address = 'oWwrvqa3QP5EHHBiUn9eAQf7d1ts5BnChG'

var signature = 'ILqvGGBI89K8Tk9/BgrGPSMTB9ZY+Z88Z0GjVsx7uPTwOfQ+eNj/VZKZ40iSbUPgz6mSBvo6w1Dkzns9DqfYa2o='

var message = 'Hey this is Ranchi Mall' console.log(bitcoinMessage.verify(message, address, signature))

// => true

References