UNPKG

2.74 kBMarkdownView Raw
1# Public Key
2Represents a ECDSA public key and is needed to be able to receive cryptocurrencies, as is usually represented as a cryptocurrency address.
3
4A PublicKey in KeyLib is an immutable object and can be instantiated from a [Point](crypto.md), string, [PrivateKey](privatekey.md), Buffer or a [BN](crypto.md).
5
6## Instantiate a Public Key
7Here is how to instantiate a public key:
8
9```javascript
10
11var privateKey = new PrivateKey();
12
13// from a private key
14var publicKey = new PublicKey(privateKey);
15
16// from a der hex encoded string
17var publicKey2 = new PublicKey('02a1633cafcc01ebfb6d78e39f687a1f0995c62fc95f51ead10a02ee0be551b5dc');
18```
19
20## Validating a Public Key
21A public key point should be on the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1) curve, instantiating a new PublicKey will validate this and will throw an error if it's invalid. To check that a public key is valid:
22
23```javascript
24if (PublicKey.isValid('02a1633cafcc01ebfb6d78e39f687a1f0995c62fc95f51ead10a02ee0be551b5dc')){
25 // valid public key
26}
27```
28
29## Compressed vs Uncompressed
30It's important to note that there are two possible ways to represent a public key. The standard is _compressed_ and includes the X value and parity (as represented above in the documentation). There is also a longer version that is _uncompressed_ which includes both X and Y values. Using this encoding will generate a different bitcoin address, so be careful when selecting the encoding. Uncompressed public keys start with 0x04; compressed public keys begin with 0x03 or 0x02 depending on whether they're greater or less than the midpoint of the curve. These prefix bytes are all used in official secp256k1 documentation.
31
32Example:
33
34```javascript
35> var keyLib = require('@owstack/key-lib');
36
37// compressed public key starting with 0x03 (greater than midpoint of curve)
38> var compressedPK = keyLib.PublicKey('030589ee559348bd6a7325994f9c8eff12bd'+
39 '5d73cc683142bd0dd1a17abc99b0dc');
40> compressedPK.compressed;
41true
42> compressedPK.toAddress().toString();
43'1KbUJ4x8epz6QqxkmZbTc4f79JbWWz6g37'
44// compressed public key starting with 0x02 (smaller than midpoint of curve)
45> var compressedPK2 = new keyLib.PublicKey('02a1633cafcc01ebfb6d78e39f687a1f'+
46 '0995c62fc95f51ead10a02ee0be551b5dc');
47> compressedPK2.compressed;
48true
49> compressedPK.toAddress().toString();
50'1KbUJ4x8epz6QqxkmZbTc4f79JbWWz6g37'
51// uncompressed public key, starting with 0x04. Contains both X and Y encoded
52> var uncompressed = keyLib.PublicKey('0479BE667EF9DCBBAC55A06295CE870B07029'+
53 'BFCDB2DCE28D959F2815B16F81798483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68'+
54 '554199C47D08FFB10D4B8');
55> uncompressed.compressed
56false
57> uncompressed.toAddress().toString()
58'1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm'
59```