How to convert a keyPair to JSON and back?

1

Using bitcoinjs you can generate a keyPair with the following code:

var keyPair = bitcoin.ECPair.makeRandom();

How can I stringify this object to JSON and then parse it back to an object? JSON doesn't play well with circular objects and I'm struggling to understand how one can work around this.

Thanks,

Connor

user1929274

Posted 2016-12-05T13:28:18.700

Reputation: 63

Why would you stringify keyPair? Is it the public key / private key / address you wish to use for further processing? Or the details in the keyPair object?Shabahat M. Ayubi 2016-12-06T11:27:02.473

@ShabahatM.Ayubi I wish to use details in the keyPair object. Specifically I'm trying to see if I can essentially transfer the entire keyPair from one device to another. (I understand this would be a horrible idea security wise if the keyPairs were actively being used for their original purpose)user1929274 2016-12-06T15:15:11.170

I fail to understand why would you do that. I tried going through the src folder of bitcoinjs-lib module. The ECpair go through tonnes of calculations before being converted into some form which is useful. Also I cannot understand the difference between JSON and object, both are the same. Do you wish to convert a JSON to string and vice versa?Shabahat M. Ayubi 2016-12-07T11:41:41.617

Answers

1

Wallet Import Format can be used in a Javascript String, which is JSON compatible. For bitcoinjs-lib@^2.0.0:

var prv = keyPair.toWIF()

To recover, use

bitcoin.ECPair.fromWIF(prv)

Caution: if you store your private key in an insecure location, your funds will be insecure. fromWIF/toWIF does not provide any form of protection.

deceleratedcaviar

Posted 2016-12-05T13:28:18.700

Reputation: 131