UNPKG

1.8 kBMarkdownView Raw
1# Private Key
2
3Represents a bitcoin private key and is needed to be able to spend bitcoin and sign transactions. See the official [Bitcoin Wiki](https://en.bitcoin.it/wiki/Private_key) for more information about private keys. A PrivateKey in Bitcore is an immutable object that has methods to import and export into a variety of formats including [Wallet Import Format](https://en.bitcoin.it/wiki/Wallet_import_format).
4
5## Instantiate a Private Key
6
7Here is how to create a new private key. It will generate a new random number using `window.crypto` or the Node.js `crypto` library.
8
9```javascript
10var privateKey = new PrivateKey();
11
12// Creates a private key from a hexa encoded number
13var privateKey2 = new PrivateKey('b221d9dbb083a7f33428d7c2a3c3198ae925614d70210e28716ccaa7cd4ddb79');
14```
15
16To export and import a private key, you can do the following:
17
18```javascript
19// encode into wallet export format
20var exported = privateKey.toWIF();
21
22// instantiate from the exported (and saved) private key
23var imported = PrivateKey.fromWIF('L3T1s1TYP9oyhHpXgkyLoJFGniEgkv2Jhi138d7R2yJ9F4QdDU2m');
24```
25
26Note: The WIF (Wallet Import Format) includes information about the network and if the associated public key is compressed or uncompressed (thus the same bitcoin address will be generated by using this format).
27
28To generate an Address or PublicKey from a PrivateKey:
29
30```javascript
31var publicKey = privateKey.toPublicKey();
32var address = publicKey.toAddress(Networks.livenet);
33```
34
35## Validating a Private Key
36
37The code to do these validations looks like this:
38
39```javascript
40// validate an address
41if (PrivateKey.isValid(input)){
42 ...
43}
44
45// get the specific validation error that can occurred
46var error = PrivateKey.getValidationError(input, Networks.livenet);
47if (error) {
48 // handle the error
49}
50```