I'm trying to understand what a specific line of code does when signing a message using bitcoinjs-lib. Here's the code:

var bitcoin = require('bitcoinjs-lib')
var bitcoinMessage = require('bitcoinjs-message')

var keyPair = bitcoin.ECPair.makeRandom();
//private key
var privateKey = keyPair.toWIF();
// Address
var address = keyPair.getAddress();


privateKey = keyPair.d.toBuffer(32)
var message = 'your message'
var messagePrefix = bitcoin.networks.bitcoin.messagePrefix

var signature = bitcoinMessage.sign(message, messagePrefix, privateKey, keyPair.compressed)

The line I'm curious about is this one:

privateKey = keyPair.d.toBuffer(32)

What exactly is this code doing and why is it necessary?




1 Answer 1


That particular line of code asserts that the private key fits into a 32 byte-sized byte array properly with the necessary zero paddings. As the private key is simply some random Big Integer between 0 ~ 2^(256-1), javascript may encode that integer into different byte array sizes. For example, if the d value was simply 1, then it could easily fit into a 1 byte-sized byte array and you would not have the leading/trailing zeroes required depending on the endianess of your encoding of choice.

  • Ah ha! That makes sense. Thank you for the great clarification. Dec 1, 2016 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.