Sign-verify messages using bitcoinjs
Objective — You will be able to digitally sign messages with Bitcoin’s public-private key pair and verify signed message with Bitcoin’s address.
Code
Pre-setup
At the time of writing, 17 March 2019,
mkdir projectDir
cd projectDir
npm init // creates packages.json file
npm install bitcoinjs-lib --save
npm install bitcoinjs-message --save
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.
Code
var bitcoin = require('bitcoinjs-lib')
var bitcoinMessage = require('bitcoinjs-message')// Sign a message
// For Bitcoin network do not specify any network, its default
var keyPair = bitcoin.ECPair.fromWIF('KyatKtdVaboeVJ8nE1g5VvQpU23R5pezeVvK9bvZxPLSwUh9SJ5J')//var privateKey = keyPair.d.toBuffer(32) // v3.x.x
var privateKey = keyPair.privateKey // v4.x.xvar message = 'Hey I am Kenneth Hu'
var signature = bitcoinMessage.sign(message, privateKey, keyPair.compressed)console.log(signature.toString('base64'))
// => 'H2W5ToC4QVri8f95yeywh+V1G4ds76RXTGHrxRZ2+oJIXEs95phNU4lH5QhHO1UgJFjXgaBGTcnsRKB8e2CT2Jc='
// Verify a message
var address = '1PYxHnYb9yjKAy7tjc4W8N9JwU6hZp65L4'
var signature = signature.toString('base64');
var message = 'Hey I am Kenneth Hu'
console.log("\nResult : ", bitcoinMessage.verify(message, address, signature))var ErrorMessage = 'Hey I am Kenneth'
console.log("\n\nResult : ", bitcoinMessage.verify(ErrorMessage, address, signature))
References
I do this because I love it, but if you want me to buy me a cup of coffee I won’t say no :O )Thanks ^^
donation :
XEM : NCWZSUF4FPXJY3L3Y7657QNVBIUZ5D54F4TNJ64S
Ether : 0xf2d15dEAf62b8c4AFC0343006579E8E662c120D9
Bitcoin : 332UiyAfSXyvhqCYgDgBkNLFSf25ccNV9i
*Do CLAP, COMMENT and SHARE! I also welcome any business opportunities that arises**