1 | var ecurve = require('ecurve')
|
2 | var ECPointFp = ecurve.ECPointFp
|
3 | var ecparams = ecurve.getECParams('secp256k1')
|
4 | var BigInteger = require('bigi')
|
5 |
|
6 | module.exports = ECKey
|
7 |
|
8 |
|
9 | function ECKey (bytes, compressed) {
|
10 | if (!(this instanceof ECKey)) return new ECKey(bytes, compressed);
|
11 |
|
12 | if (typeof compressed == 'boolean')
|
13 | this._compressed = compressed
|
14 | else
|
15 | this._compressed = true
|
16 |
|
17 | if (bytes)
|
18 | this.privateKey = bytes;
|
19 | }
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | Object.defineProperty(ECKey.prototype, 'privateKey', {
|
26 | enumerable: true, configurable: true,
|
27 | get: function() {
|
28 | return this.key;
|
29 | },
|
30 | set: function(bytes) {
|
31 | var byteArr;
|
32 | if (Buffer.isBuffer(bytes)) {
|
33 | this.key = bytes;
|
34 | byteArr = [].slice.call(bytes);
|
35 | } else if (bytes instanceof Uint8Array) {
|
36 | byteArr = [].slice.call(bytes);
|
37 | this.key = new Buffer(byteArr);
|
38 | } else if (Array.isArray(bytes)) {
|
39 | byteArr = bytes;
|
40 | this.key = new Buffer(byteArr);
|
41 | } else {
|
42 | throw new Error('Invalid type. private key bytes must be either a Buffer, Array, or Uint8Array.');
|
43 | }
|
44 |
|
45 | if (bytes.length != 32)
|
46 | throw new Error("private key bytes must have a length of 32");
|
47 |
|
48 |
|
49 | if (this._compressed)
|
50 | this._exportKey = Buffer.concat([ this.key, new Buffer([0x01]) ]);
|
51 | else
|
52 | this._exportKey = Buffer.concat([ this.key ]);
|
53 |
|
54 | this.keyBigInteger = BigInteger.fromByteArrayUnsigned(byteArr);
|
55 |
|
56 |
|
57 | this._publicPoint = null;
|
58 | this._pubKeyHash = null;
|
59 | }
|
60 | })
|
61 |
|
62 | Object.defineProperty(ECKey.prototype, 'privateExportKey', {
|
63 | get: function() {
|
64 | return this._exportKey;
|
65 | }
|
66 | })
|
67 |
|
68 | Object.defineProperty(ECKey.prototype, 'publicKey', {
|
69 | get: function() {
|
70 | return new Buffer(this.publicPoint.getEncoded(this.compressed));
|
71 | }
|
72 | })
|
73 |
|
74 | Object.defineProperty(ECKey.prototype, 'publicPoint', {
|
75 | get: function() {
|
76 | if (!this._publicPoint) {
|
77 | this._publicPoint = ecparams.g.multiply(this.keyBigInteger);
|
78 | }
|
79 | return this._publicPoint;
|
80 | }
|
81 | })
|
82 |
|
83 | Object.defineProperty(ECKey.prototype, 'compressed', {
|
84 | get: function() {
|
85 | return this._compressed;
|
86 | },
|
87 | set: function(val) {
|
88 | var c = !!val;
|
89 | if (c === this._compressed) return;
|
90 |
|
91 |
|
92 | var pk = this.privateKey;
|
93 | this._compressed = c;
|
94 | this.privateKey = pk;
|
95 | }
|
96 | })
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 | ECKey.prototype.toString = function (format) {
|
104 | return this.privateKey.toString('hex');
|
105 | }
|
106 |
|
107 |
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|