Browse Source

v0.0.4: update (and partial commits)

tags/v1.0.0
AJ ONeal 11 months ago
parent
commit
c71f28e1d7
10 changed files with 1352 additions and 2 deletions
  1. 5
    1
      README.md
  2. 235
    0
      lib/asn1.js
  3. 493
    0
      lib/eckles.js
  4. 42
    0
      lib/encoding.js
  5. 28
    0
      lib/pem.js
  6. 204
    0
      lib/rasha.js
  7. 80
    0
      lib/ssh.js
  8. 111
    0
      lib/telemetry.js
  9. 153
    0
      lib/x509.js
  10. 1
    1
      package.json

+ 5
- 1
README.md View File

@@ -1,10 +1,14 @@
1 1
 This is being ported from code from rsa-compat.js, greenlock.html (bacme.js), and others.
2 2
 
3
-This is my project for the weekend. I expect to be finished today (Monday Nov 12th, 2018)
3
+This was intended to be just a weekend project, but it's grown a bit.
4
+
4 5
 * 2018-10-10 (Saturday) work has begun
5 6
 * 2018-10-11 (Sunday) W00T! got a CSR generated for RSA with VanillaJS ArrayBuffer
6 7
 * 2018-10-12 (Monday) Figuring out ECDSA CSRs right now
7 8
 * 2018-10-15 (Thursday) ECDSA is a trixy hobbit... but I think I've got it...
9
+* 2018-12-02 (Sunday) Been mostly done for a while, individually, slowly merging everything together
10
+  * [Rasha.js](https://git.coolaj86.com/coolaj86/rasha.js) (RSA utils)
11
+  * [Eckles.js](https://git.coolaj86.com/coolaj86/eckles.js) (EC utils)
8 12
 
9 13
 <!--
10 14
 Keypairs&trade; for node.js

+ 235
- 0
lib/asn1.js View File

@@ -0,0 +1,235 @@
1
+'use strict';
2
+
3
+//
4
+// A dumbed-down, minimal ASN.1 parser / packer combo
5
+//
6
+// Note: generally I like to write congruent code
7
+// (i.e. output can be used as input and vice-versa)
8
+// However, this seemed to be more readable and easier
9
+// to use written as-is, asymmetrically.
10
+// (I also generally prefer to export objects rather
11
+// functions but, yet again, asthetics one in this case)
12
+
13
+var Enc = require('./encoding.js');
14
+
15
+//
16
+// Packer
17
+//
18
+
19
+// Almost every ASN.1 type that's important for CSR
20
+// can be represented generically with only a few rules.
21
+var ASN1 = module.exports = function ASN1(/*type, hexstrings...*/) {
22
+  var args = Array.prototype.slice.call(arguments);
23
+  var typ = args.shift();
24
+  var str = args.join('').replace(/\s+/g, '').toLowerCase();
25
+  var len = (str.length/2);
26
+  var lenlen = 0;
27
+  var hex = typ;
28
+
29
+  // We can't have an odd number of hex chars
30
+  if (len !== Math.round(len)) {
31
+    throw new Error("invalid hex");
32
+  }
33
+
34
+  // The first byte of any ASN.1 sequence is the type (Sequence, Integer, etc)
35
+  // The second byte is either the size of the value, or the size of its size
36
+
37
+  // 1. If the second byte is < 0x80 (128) it is considered the size
38
+  // 2. If it is > 0x80 then it describes the number of bytes of the size
39
+  //    ex: 0x82 means the next 2 bytes describe the size of the value
40
+  // 3. The special case of exactly 0x80 is "indefinite" length (to end-of-file)
41
+
42
+  if (len > 127) {
43
+    lenlen += 1;
44
+    while (len > 255) {
45
+      lenlen += 1;
46
+      len = len >> 8;
47
+    }
48
+  }
49
+
50
+  if (lenlen) { hex += Enc.numToHex(0x80 + lenlen); }
51
+  return hex + Enc.numToHex(str.length/2) + str;
52
+};
53
+
54
+// The Integer type has some special rules
55
+ASN1.UInt = function UINT() {
56
+  var str = Array.prototype.slice.call(arguments).join('');
57
+  var first = parseInt(str.slice(0, 2), 16);
58
+
59
+  // If the first byte is 0x80 or greater, the number is considered negative
60
+  // Therefore we add a '00' prefix if the 0x80 bit is set
61
+  if (0x80 & first) { str = '00' + str; }
62
+
63
+  return ASN1('02', str);
64
+};
65
+
66
+// The Bit String type also has a special rule
67
+ASN1.BitStr = function BITSTR() {
68
+  var str = Array.prototype.slice.call(arguments).join('');
69
+  // '00' is a mask of how many bits of the next byte to ignore
70
+  return ASN1('03', '00' + str);
71
+};
72
+
73
+
74
+//
75
+// Parser
76
+//
77
+
78
+ASN1.ELOOP = "uASN1.js Error: iterated over 15+ elements (probably a malformed file)";
79
+ASN1.EDEEP = "uASN1.js Error: element nested 20+ layers deep (probably a malformed file)";
80
+// Container Types are Sequence 0x30, Octect String 0x04, Array? (0xA0, 0xA1)
81
+// Value Types are Integer 0x02, Bit String 0x03, Null 0x05, Object ID 0x06,
82
+// Sometimes Bit String is used as a container (RSA Pub Spki)
83
+ASN1.VTYPES = [ 0x02, 0x03, 0x05, 0x06, 0x0c, 0x82 ];
84
+ASN1.parse = function parseAsn1(buf, depth, ws) {
85
+  if (!ws) { ws = ''; }
86
+  if (depth >= 20) { throw new Error(ASN1.EDEEP); }
87
+
88
+  var index = 2; // we know, at minimum, data starts after type (0) and lengthSize (1)
89
+  var asn1 = { type: buf[0], lengthSize: 0, length: buf[1] };
90
+  var child;
91
+  var iters = 0;
92
+  var adjust = 0;
93
+  var adjustedLen;
94
+
95
+  // Determine how many bytes the length uses, and what it is
96
+  if (0x80 & asn1.length) {
97
+    asn1.lengthSize = 0x7f & asn1.length;
98
+    // I think that buf->hex->int solves the problem of Endianness... not sure
99
+    asn1.length = parseInt(Enc.bufToHex(buf.slice(index, index + asn1.lengthSize)), 16);
100
+    index += asn1.lengthSize;
101
+  }
102
+
103
+  // High-order bit Integers have a leading 0x00 to signify that they are positive.
104
+  // Bit Streams use the first byte to signify padding, which x.509 doesn't use.
105
+  if (0x00 === buf[index] && (0x02 === asn1.type || 0x03 === asn1.type)) {
106
+    // However, 0x00 on its own is a valid number
107
+    if (asn1.length > 1) {
108
+      index += 1;
109
+      adjust = -1;
110
+    }
111
+  }
112
+  adjustedLen = asn1.length + adjust;
113
+
114
+  //console.warn(ws + '0x' + Enc.numToHex(asn1.type), index, 'len:', asn1.length, asn1);
115
+
116
+  // this is a primitive value type
117
+  if (-1 !== ASN1.VTYPES.indexOf(asn1.type)) {
118
+    asn1.value = buf.slice(index, index + adjustedLen);
119
+    return asn1;
120
+  }
121
+
122
+  asn1.children = [];
123
+  //console.warn('1 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', 0);
124
+  while (iters < 15 && index < (2 + asn1.length + asn1.lengthSize)) {
125
+    iters += 1;
126
+    child = ASN1.parse(buf.slice(index, index + adjustedLen), (depth || 0) + 1, ws + '  ');
127
+    // The numbers don't match up exactly and I don't remember why...
128
+    // probably something with adjustedLen or some such, but the tests pass
129
+    index += (2 + child.lengthSize + child.length);
130
+    //console.warn('2 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', (2 + child.lengthSize + child.length));
131
+    if (index > (2 + asn1.lengthSize + asn1.length)) {
132
+      console.error(JSON.stringify(asn1, function (k, v) {
133
+        if ('value' === k) { return '0x' + Enc.bufToHex(v.data); } return v;
134
+      }, 2));
135
+      throw new Error("Parse error: child value length (" + child.length
136
+        + ") is greater than remaining parent length (" + (asn1.length - index)
137
+        + " = " + asn1.length + " - " + index + ")");
138
+    }
139
+    asn1.children.push(child);
140
+    //console.warn(ws + '0x' + Enc.numToHex(asn1.type), index, 'len:', asn1.length, asn1);
141
+  }
142
+  if (index !== (2 + asn1.lengthSize + asn1.length)) {
143
+    console.warn('index:', index, 'length:', (2 + asn1.lengthSize + asn1.length))
144
+    throw new Error("premature end-of-file");
145
+  }
146
+  if (iters >= 15) { throw new Error(ASN1.ELOOP); }
147
+
148
+  return asn1;
149
+};
150
+
151
+/*
152
+ASN1._stringify = function(asn1) {
153
+  //console.log(JSON.stringify(asn1, null, 2));
154
+  //console.log(asn1);
155
+  var ws = '';
156
+
157
+  function write(asn1) {
158
+    console.log(ws, 'ch', Enc.numToHex(asn1.type), asn1.length);
159
+    if (!asn1.children) {
160
+      return;
161
+    }
162
+    asn1.children.forEach(function (a) {
163
+      ws += '\t';
164
+      write(a);
165
+      ws = ws.slice(1);
166
+    });
167
+  }
168
+  write(asn1);
169
+};
170
+*/
171
+
172
+ASN1.tpl = function (asn1) {
173
+  //console.log(JSON.stringify(asn1, null, 2));
174
+  //console.log(asn1);
175
+  var sp = '  ';
176
+  var ws = sp;
177
+  var i = 0;
178
+  var vars = [];
179
+  var str = ws;
180
+
181
+  function write(asn1, k) {
182
+    str += "\n" + ws;
183
+    var val;
184
+    if ('number' !== typeof k) {
185
+      // ignore
186
+    } else {
187
+      str += ', ';
188
+    }
189
+    if (0x02 === asn1.type) {
190
+      str += "ASN1.UInt(";
191
+    } else if (0x03 === asn1.type) {
192
+      str += "ASN1.BitStr(";
193
+    } else {
194
+      str += "ASN1('" + Enc.numToHex(asn1.type) + "'";
195
+    }
196
+    if (!asn1.children) {
197
+      if (0x05 !== asn1.type) {
198
+        if (0x06 !== asn1.type) {
199
+          val = asn1.value || new Uint8Array(0);
200
+          vars.push("\n// 0x" + Enc.numToHex(val.byteLength) + " (" + val.byteLength + " bytes)\nopts.tpl" + i + " = '"
201
+            + Enc.bufToHex(val) + "';");
202
+          if (0x02 !== asn1.type && 0x03 !== asn1.type) {
203
+            str += ", ";
204
+          }
205
+          str += "Enc.bufToHex(opts.tpl" + i + ")";
206
+        } else {
207
+          str += ", '" + Enc.bufToHex(asn1.value) + "'";
208
+        }
209
+      } else {
210
+        console.warn("XXXXXXXXXXXXXXXXXXXXX");
211
+      }
212
+      str += ")";
213
+      return ;
214
+    }
215
+    asn1.children.forEach(function (a, j) {
216
+      i += 1;
217
+      ws += sp;
218
+      write(a, j);
219
+      ws = ws.slice(sp.length);
220
+    });
221
+    str += "\n" + ws + ")";
222
+  }
223
+
224
+  write(asn1);
225
+  console.log('var opts = {};');
226
+  console.log(vars.join('\n') + '\n');
227
+  console.log();
228
+  console.log('function buildSchema(opts) {');
229
+  console.log(sp + 'return Enc.hexToBuf(' + str.slice(3) + ');');
230
+  console.log('}');
231
+  console.log();
232
+  console.log('buildSchema(opts);');
233
+};
234
+
235
+module.exports = ASN1;

+ 493
- 0
lib/eckles.js View File

@@ -0,0 +1,493 @@
1
+'use strict';
2
+
3
+var EC = module.exports;
4
+
5
+var Enc = require('./encoding.js');
6
+var ASN1;
7
+var PEM = require('./pem.js');
8
+
9
+// 1.2.840.10045.3.1.7
10
+// prime256v1 (ANSI X9.62 named elliptic curve)
11
+var OBJ_ID_EC  = '06 08 2A8648CE3D030107'.replace(/\s+/g, '').toLowerCase();
12
+// 1.3.132.0.34
13
+// secp384r1 (SECG (Certicom) named elliptic curve)
14
+var OBJ_ID_EC_384 = '06 05 2B81040022'.replace(/\s+/g, '').toLowerCase();
15
+
16
+// 1.2.840.10045.2.1
17
+// ecPublicKey (ANSI X9.62 public key type)
18
+var OBJ_ID_EC_PUB = '06 07 2A8648CE3D0201'.replace(/\s+/g, '').toLowerCase();
19
+
20
+                      // 19  e  c  d  s  a  -  s  h  a  2  -  n  i  s  t  p  2  5  6
21
+var SSH_EC_P256 = '00000013 65 63 64 73 61 2d 73 68 61 32 2d 6e 69 73 74 70 32 35 36'
22
+  .replace(/\s+/g, '').toLowerCase();
23
+
24
+                      // 19  e  c  d  s  a  -  s  h  a  2  -  n  i  s  t  p  3  8  4
25
+var SSH_EC_P384 = '00000013 65 63 64 73 61 2d 73 68 61 32 2d 6e 69 73 74 70 33 38 34'
26
+  .replace(/\s+/g, '').toLowerCase();
27
+
28
+// The one good thing that came from the b***kchain hysteria: good EC documentation
29
+// https://davidederosa.com/basic-blockchain-programming/elliptic-curve-keys/
30
+
31
+EC.parseSec1 = function parseEcOnlyPrivkey(u8, jwk) {
32
+  var index = 7;
33
+  var len = 32;
34
+  var olen = OBJ_ID_EC.length/2;
35
+
36
+  if ("P-384" === jwk.crv) {
37
+    olen = OBJ_ID_EC_384.length/2;
38
+    index = 8;
39
+    len = 48;
40
+  }
41
+  if (len !== u8[index - 1]) {
42
+    throw new Error("Unexpected bitlength " + len);
43
+  }
44
+
45
+  // private part is d
46
+  var d = u8.slice(index, index + len);
47
+  // compression bit index
48
+  var ci = index + len + 2 + olen + 2 + 3;
49
+  var c = u8[ci];
50
+  var x, y;
51
+
52
+  if (0x04 === c) {
53
+    y = u8.slice(ci + 1 + len, ci + 1 + len + len);
54
+  } else if (0x02 !== c) {
55
+    throw new Error("not a supported EC private key");
56
+  }
57
+  x = u8.slice(ci + 1, ci + 1 + len);
58
+
59
+  return {
60
+    kty: jwk.kty
61
+  , crv: jwk.crv
62
+  , d: Enc.bufToUrlBase64(d)
63
+  //, dh: Enc.bufToHex(d)
64
+  , x: Enc.bufToUrlBase64(x)
65
+  //, xh: Enc.bufToHex(x)
66
+  , y: Enc.bufToUrlBase64(y)
67
+  //, yh: Enc.bufToHex(y)
68
+  };
69
+};
70
+
71
+EC.parsePkcs8 = function parseEcPkcs8(u8, jwk) {
72
+  var index = 24 + (OBJ_ID_EC.length/2);
73
+  var len = 32;
74
+  if ("P-384" === jwk.crv) {
75
+    index = 24 + (OBJ_ID_EC_384.length/2) + 2;
76
+    len = 48;
77
+  }
78
+
79
+  //console.log(index, u8.slice(index));
80
+  if (0x04 !== u8[index]) {
81
+    //console.log(jwk);
82
+    throw new Error("privkey not found");
83
+  }
84
+  var d = u8.slice(index+2, index+2+len);
85
+  var ci = index+2+len+5;
86
+  var xi = ci+1;
87
+  var x = u8.slice(xi, xi + len);
88
+  var yi = xi+len;
89
+  var y;
90
+  if (0x04 === u8[ci]) {
91
+    y = u8.slice(yi, yi + len);
92
+  } else if (0x02 !== u8[ci]) {
93
+    throw new Error("invalid compression bit (expected 0x04 or 0x02)");
94
+  }
95
+
96
+  return {
97
+    kty: jwk.kty
98
+  , crv: jwk.crv
99
+  , d: Enc.bufToUrlBase64(d)
100
+  //, dh: Enc.bufToHex(d)
101
+  , x: Enc.bufToUrlBase64(x)
102
+  //, xh: Enc.bufToHex(x)
103
+  , y: Enc.bufToUrlBase64(y)
104
+  //, yh: Enc.bufToHex(y)
105
+  };
106
+};
107
+
108
+EC.parseSpki = function parsePem(u8, jwk) {
109
+  var ci = 16 + OBJ_ID_EC.length/2;
110
+  var len = 32;
111
+
112
+  if ("P-384" === jwk.crv) {
113
+    ci = 16 + OBJ_ID_EC_384.length/2;
114
+    len = 48;
115
+  }
116
+
117
+  var c = u8[ci];
118
+  var xi = ci + 1;
119
+  var x = u8.slice(xi, xi + len);
120
+  var yi = xi + len;
121
+  var y;
122
+  if (0x04 === c) {
123
+    y = u8.slice(yi, yi + len);
124
+  } else if (0x02 !== c) {
125
+    throw new Error("not a supported EC private key");
126
+  }
127
+
128
+  return {
129
+    kty: jwk.kty
130
+  , crv: jwk.crv
131
+  , x: Enc.bufToUrlBase64(x)
132
+  //, xh: Enc.bufToHex(x)
133
+  , y: Enc.bufToUrlBase64(y)
134
+  //, yh: Enc.bufToHex(y)
135
+  };
136
+};
137
+EC.parsePkix = EC.parseSpki;
138
+
139
+EC.parseSsh = function (pem) {
140
+  var jwk = { kty: 'EC', crv: null, x: null, y: null };
141
+  var b64 = pem.split(/\s+/g)[1];
142
+  var buf = Buffer.from(b64, 'base64');
143
+  var hex = Enc.bufToHex(buf);
144
+  var index = 40;
145
+  var len;
146
+  if (0 === hex.indexOf(SSH_EC_P256)) {
147
+    jwk.crv = 'P-256';
148
+    len = 32;
149
+  } else if (0 === hex.indexOf(SSH_EC_P384)) {
150
+    jwk.crv = 'P-384';
151
+    len = 48;
152
+  }
153
+  var x = buf.slice(index, index + len);
154
+  var y = buf.slice(index + len, index + len + len);
155
+  jwk.x = Enc.bufToUrlBase64(x);
156
+  jwk.y = Enc.bufToUrlBase64(y);
157
+  return jwk;
158
+};
159
+
160
+/*global Promise*/
161
+EC.generate = function (opts) {
162
+  return Promise.resolve().then(function () {
163
+    var typ = 'ec';
164
+    var format = opts.format;
165
+    var encoding = opts.encoding;
166
+    var priv;
167
+    var pub = 'spki';
168
+
169
+    if (!format) {
170
+      format = 'jwk';
171
+    }
172
+    if (-1 !== [ 'spki', 'pkcs8', 'ssh' ].indexOf(format)) {
173
+      format = 'pkcs8';
174
+    }
175
+
176
+    if ('pem' === format) {
177
+      format = 'sec1';
178
+      encoding = 'pem';
179
+    } else if ('der' === format) {
180
+      format = 'sec1';
181
+      encoding = 'der';
182
+    }
183
+
184
+    if ('jwk' === format || 'json' === format) {
185
+      format = 'jwk';
186
+      encoding = 'json';
187
+    } else {
188
+      priv = format;
189
+    }
190
+
191
+    if (!encoding) {
192
+      encoding = 'pem';
193
+    }
194
+
195
+    if (priv) {
196
+      priv = { type: priv, format: encoding };
197
+      pub = { type: pub, format: encoding };
198
+    } else {
199
+      // jwk
200
+      priv = { type: 'sec1', format: 'pem' };
201
+      pub = { type: 'spki', format: 'pem' };
202
+    }
203
+
204
+    return new Promise(function (resolve, reject) {
205
+      return require('crypto').generateKeyPair(typ, {
206
+        namedCurve: opts.crv || opts.namedCurve || 'P-256'
207
+      , privateKeyEncoding: priv
208
+      , publicKeyEncoding: pub
209
+      }, function (err, pubkey, privkey) {
210
+        if (err) { reject(err); }
211
+        resolve({
212
+          private: privkey
213
+        , public: pubkey
214
+        });
215
+      });
216
+    }).then(function (keypair) {
217
+      if ('jwk' === format) {
218
+        return {
219
+          private: EC.importSync({ pem: keypair.private, format: priv.type })
220
+        , public: EC.importSync({ pem: keypair.public, format: pub.type, public: true })
221
+        };
222
+      }
223
+
224
+      if ('ssh' !== opts.format) {
225
+        return keypair;
226
+      }
227
+
228
+      return {
229
+        private: keypair.private
230
+      , public: EC.exportSync({ jwk: EC.importSync({
231
+          pem: keypair.public, format: format, public: true
232
+        }), format: opts.format, public: true })
233
+      };
234
+    });
235
+  });
236
+};
237
+
238
+EC.importSync = function importEcSync(opts) {
239
+  if (!opts || !opts.pem || 'string' !== typeof opts.pem) {
240
+    throw new Error("must pass { pem: pem } as a string");
241
+  }
242
+  if (0 === opts.pem.indexOf('ecdsa-sha2-')) {
243
+    return EC.parseSsh(opts.pem);
244
+  }
245
+  var pem = opts.pem;
246
+  var u8 = PEM.parseBlock(pem).bytes;
247
+  var hex = Enc.bufToHex(u8);
248
+  var jwk = { kty: 'EC', crv: null, x: null, y: null };
249
+
250
+  //console.log();
251
+  if (-1 !== hex.indexOf(OBJ_ID_EC)) {
252
+    jwk.crv = "P-256";
253
+
254
+    // PKCS8
255
+    if (0x02 === u8[3] && 0x30 === u8[6] && 0x06 === u8[8]) {
256
+      //console.log("PKCS8", u8[3].toString(16), u8[6].toString(16), u8[8].toString(16));
257
+      jwk = EC.parsePkcs8(u8, jwk);
258
+    // EC-only
259
+    } else if (0x02 === u8[2] && 0x04 === u8[5] && 0xA0 === u8[39]) {
260
+      //console.log("EC---", u8[2].toString(16), u8[5].toString(16), u8[39].toString(16));
261
+      jwk = EC.parseSec1(u8, jwk);
262
+    // SPKI/PKIK (Public)
263
+    } else if (0x30 === u8[2] && 0x06 === u8[4] && 0x06 === u8[13]) {
264
+      //console.log("SPKI-", u8[2].toString(16), u8[4].toString(16), u8[13].toString(16));
265
+      jwk = EC.parseSpki(u8, jwk);
266
+    // Error
267
+    } else {
268
+      //console.log("PKCS8", u8[3].toString(16), u8[6].toString(16), u8[8].toString(16));
269
+      //console.log("EC---", u8[2].toString(16), u8[5].toString(16), u8[39].toString(16));
270
+      //console.log("SPKI-", u8[2].toString(16), u8[4].toString(16), u8[13].toString(16));
271
+      throw new Error("unrecognized key format");
272
+    }
273
+  } else if (-1 !== hex.indexOf(OBJ_ID_EC_384)) {
274
+    jwk.crv = "P-384";
275
+
276
+    // PKCS8
277
+    if (0x02 === u8[3] && 0x30 === u8[6] && 0x06 === u8[8]) {
278
+      //console.log("PKCS8", u8[3].toString(16), u8[6].toString(16), u8[8].toString(16));
279
+      jwk = EC.parsePkcs8(u8, jwk);
280
+    // EC-only
281
+    } else if (0x02 === u8[3] && 0x04 === u8[6] && 0xA0 === u8[56]) {
282
+      //console.log("EC---", u8[3].toString(16), u8[6].toString(16), u8[56].toString(16));
283
+      jwk = EC.parseSec1(u8, jwk);
284
+    // SPKI/PKIK (Public)
285
+    } else if (0x30 === u8[2] && 0x06 === u8[4] && 0x06 === u8[13]) {
286
+      //console.log("SPKI-", u8[2].toString(16), u8[4].toString(16), u8[13].toString(16));
287
+      jwk = EC.parseSpki(u8, jwk);
288
+    // Error
289
+    } else {
290
+      //console.log("PKCS8", u8[3].toString(16), u8[6].toString(16), u8[8].toString(16));
291
+      //console.log("EC---", u8[3].toString(16), u8[6].toString(16), u8[56].toString(16));
292
+      //console.log("SPKI-", u8[2].toString(16), u8[4].toString(16), u8[13].toString(16));
293
+      throw new Error("unrecognized key format");
294
+    }
295
+  } else {
296
+    throw new Error("Supported key types are P-256 and P-384");
297
+  }
298
+  if (opts.public) {
299
+    if (true !== opts.public) {
300
+      throw new Error("options.public must be either `true` or `false` not ("
301
+        + typeof opts.public + ") '" + opts.public + "'");
302
+    }
303
+    delete jwk.d;
304
+  }
305
+  return jwk;
306
+};
307
+EC.parse = function parseEc(opts) {
308
+  return Promise.resolve().then(function () {
309
+    return EC.importSync(opts);
310
+  });
311
+};
312
+EC.toJwk = EC.import = EC.parse;
313
+
314
+EC.exportSync = function (opts) {
315
+  if (!opts || !opts.jwk || 'object' !== typeof opts.jwk) {
316
+    throw new Error("must pass { jwk: jwk } as a JSON object");
317
+  }
318
+  var jwk = JSON.parse(JSON.stringify(opts.jwk));
319
+  var format = opts.format;
320
+  if (opts.public || -1 !== [ 'spki', 'pkix', 'ssh', 'rfc4716' ].indexOf(format)) {
321
+    jwk.d = null;
322
+  }
323
+  if ('EC' !== jwk.kty) {
324
+    throw new Error("options.jwk.kty must be 'EC' for EC keys");
325
+  }
326
+  if (!jwk.d) {
327
+    if (!format || -1 !== [ 'spki', 'pkix' ].indexOf(format)) {
328
+      format = 'spki';
329
+    } else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
330
+      format = 'ssh';
331
+    } else {
332
+      throw new Error("options.format must be 'spki' or 'ssh' for public EC keys, not ("
333
+        + typeof format + ") " + format);
334
+    }
335
+  } else {
336
+    if (!format || 'sec1' === format) {
337
+      format = 'sec1';
338
+    } else if ('pkcs8' !== format) {
339
+      throw new Error("options.format must be 'sec1' or 'pkcs8' for private EC keys, not '" + format + "'");
340
+    }
341
+  }
342
+  if (-1 === [ 'P-256', 'P-384' ].indexOf(jwk.crv)) {
343
+    throw new Error("options.jwk.crv must be either P-256 or P-384 for EC keys, not '" + jwk.crv + "'");
344
+  }
345
+  if (!jwk.y) {
346
+    throw new Error("options.jwk.y must be a urlsafe base64-encoded either P-256 or P-384");
347
+  }
348
+
349
+  if ('sec1' === format) {
350
+    return PEM.packBlock({ type: "EC PRIVATE KEY", bytes: EC.packSec1(jwk) });
351
+  } else if ('pkcs8' === format) {
352
+    return PEM.packBlock({ type: "PRIVATE KEY", bytes: EC.packPkcs8(jwk) });
353
+  } else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
354
+    return PEM.packBlock({ type: "PUBLIC KEY", bytes: EC.packSpki(jwk) });
355
+  } else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
356
+    return EC.packSsh(jwk);
357
+  } else {
358
+    throw new Error("Sanity Error: reached unreachable code block with format: " + format);
359
+  }
360
+};
361
+EC.pack = function (opts) {
362
+  return Promise.resolve().then(function () {
363
+    return EC.exportSync(opts);
364
+  });
365
+};
366
+
367
+EC.packSec1 = function (jwk) {
368
+  var d = Enc.base64ToHex(jwk.d);
369
+  var x = Enc.base64ToHex(jwk.x);
370
+  var y = Enc.base64ToHex(jwk.y);
371
+  var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
372
+  return Enc.hexToUint8(
373
+    ASN1('30'
374
+    , ASN1.UInt('01')
375
+    , ASN1('04', d)
376
+    , ASN1('A0', objId)
377
+    , ASN1('A1', ASN1.BitStr('04' + x + y)))
378
+  );
379
+};
380
+EC.packPkcs8 = function (jwk) {
381
+  var d = Enc.base64ToHex(jwk.d);
382
+  var x = Enc.base64ToHex(jwk.x);
383
+  var y = Enc.base64ToHex(jwk.y);
384
+  var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
385
+  return Enc.hexToUint8(
386
+    ASN1('30'
387
+    , ASN1.UInt('00')
388
+    , ASN1('30'
389
+      , OBJ_ID_EC_PUB
390
+      , objId
391
+      )
392
+    , ASN1('04'
393
+      , ASN1('30'
394
+        , ASN1.UInt('01')
395
+        , ASN1('04', d)
396
+        , ASN1('A1', ASN1.BitStr('04' + x + y)))))
397
+  );
398
+};
399
+EC.packSpki = function (jwk) {
400
+  var x = Enc.base64ToHex(jwk.x);
401
+  var y = Enc.base64ToHex(jwk.y);
402
+  var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
403
+  return Enc.hexToUint8(
404
+    ASN1('30'
405
+    , ASN1('30'
406
+      , OBJ_ID_EC_PUB
407
+      , objId
408
+      )
409
+    , ASN1.BitStr('04' + x + y))
410
+  );
411
+};
412
+EC.packPkix = EC.packSpki;
413
+EC.packSsh = function (jwk) {
414
+  // Custom SSH format
415
+  var typ = 'ecdsa-sha2-nistp256';
416
+	var a = '32 35 36';
417
+  var b = '41';
418
+  var comment = jwk.crv + '@localhost';
419
+  if ('P-256' !== jwk.crv) {
420
+    typ = 'ecdsa-sha2-nistp384';
421
+    a = '33 38 34';
422
+    b = '61';
423
+  }
424
+  var x = Enc.base64ToHex(jwk.x);
425
+  var y = Enc.base64ToHex(jwk.y);
426
+  var ssh = Enc.hexToUint8(
427
+    ('00 00 00 13 65 63 64 73 61 2d 73 68 61 32 2d 6e 69 73 74 70'
428
+    + a + '00 00 00 08 6e 69 73 74 70' + a + '00 00 00' + b
429
+    + '04' + x + y).replace(/\s+/g, '').toLowerCase()
430
+  );
431
+
432
+  return typ + ' ' + Enc.bufToBase64(ssh) + ' ' + comment;
433
+};
434
+
435
+//
436
+// A dumbed-down, minimal ASN.1 packer
437
+//
438
+
439
+// Almost every ASN.1 type that's important for CSR
440
+// can be represented generically with only a few rules.
441
+ASN1 = function ASN1(/*type, hexstrings...*/) {
442
+  var args = Array.prototype.slice.call(arguments);
443
+  var typ = args.shift();
444
+  var str = args.join('').replace(/\s+/g, '').toLowerCase();
445
+  var len = (str.length/2);
446
+  var lenlen = 0;
447
+  var hex = typ;
448
+
449
+  // We can't have an odd number of hex chars
450
+  if (len !== Math.round(len)) {
451
+    throw new Error("invalid hex");
452
+  }
453
+
454
+  // The first byte of any ASN.1 sequence is the type (Sequence, Integer, etc)
455
+  // The second byte is either the size of the value, or the size of its size
456
+
457
+  // 1. If the second byte is < 0x80 (128) it is considered the size
458
+  // 2. If it is > 0x80 then it describes the number of bytes of the size
459
+  //    ex: 0x82 means the next 2 bytes describe the size of the value
460
+  // 3. The special case of exactly 0x80 is "indefinite" length (to end-of-file)
461
+
462
+  if (len > 127) {
463
+    lenlen += 1;
464
+    while (len > 255) {
465
+      lenlen += 1;
466
+      len = len >> 8;
467
+    }
468
+  }
469
+
470
+  if (lenlen) { hex += Enc.numToHex(0x80 + lenlen); }
471
+  return hex + Enc.numToHex(str.length/2) + str;
472
+};
473
+
474
+// The Integer type has some special rules
475
+ASN1.UInt = function UINT() {
476
+  var str = Array.prototype.slice.call(arguments).join('');
477
+  var first = parseInt(str.slice(0, 2), 16);
478
+
479
+  // If the first byte is 0x80 or greater, the number is considered negative
480
+  // Therefore we add a '00' prefix if the 0x80 bit is set
481
+  if (0x80 & first) { str = '00' + str; }
482
+
483
+  return ASN1('02', str);
484
+};
485
+
486
+// The Bit String type also has a special rule
487
+ASN1.BitStr = function BITSTR() {
488
+  var str = Array.prototype.slice.call(arguments).join('');
489
+  // '00' is a mask of how many bits of the next byte to ignore
490
+  return ASN1('03', '00' + str);
491
+};
492
+
493
+EC.toPem = EC.export = EC.pack;

+ 42
- 0
lib/encoding.js View File

@@ -0,0 +1,42 @@
1
+'use strict';
2
+
3
+var Enc = module.exports;
4
+
5
+Enc.base64ToBuf = function (str) {
6
+  // node handles both base64 and urlBase64 equally
7
+  return Buffer.from(str, 'base64');
8
+};
9
+
10
+Enc.base64ToHex = function (b64) {
11
+  return Enc.bufToHex(Enc.base64ToBuf(b64));
12
+};
13
+
14
+Enc.bufToBase64 = function (u8) {
15
+  // Ensure a node buffer, even if TypedArray
16
+  return Buffer.from(u8).toString('base64');
17
+};
18
+
19
+Enc.bufToHex = function (u8) {
20
+  // Ensure a node buffer, even if TypedArray
21
+  return Buffer.from(u8).toString('hex');
22
+};
23
+
24
+Enc.bufToUrlBase64 = function (u8) {
25
+  return Enc.bufToBase64(u8)
26
+    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
27
+};
28
+
29
+Enc.hexToUint8 = function (hex) {
30
+  // TODO: I don't remember why I chose Uint8Array over Buffer...
31
+  var buf = Buffer.from(hex, 'hex');
32
+  var ab = buf.buffer.slice(buf.offset, buf.offset + buf.byteLength);
33
+  return new Uint8Array(ab);
34
+};
35
+
36
+Enc.numToHex = function (d) {
37
+  d = d.toString(16);
38
+  if (d.length % 2) {
39
+    return '0' + d;
40
+  }
41
+  return d;
42
+};

+ 28
- 0
lib/pem.js View File

@@ -0,0 +1,28 @@
1
+'use strict';
2
+
3
+var PEM = module.exports;
4
+var Enc = require('./encoding.js');
5
+
6
+PEM.parseBlock = function pemToDer(pem) {
7
+  var lines = pem.trim().split(/\n/);
8
+  var end = lines.length - 1;
9
+  var head = lines[0].match(/-----BEGIN (.*)-----/);
10
+  var foot = lines[end].match(/-----END (.*)-----/);
11
+
12
+  if (head) {
13
+    lines = lines.slice(1, end);
14
+    head = head[1];
15
+    if (head !== foot[1]) {
16
+      throw new Error("headers and footers do not match");
17
+    }
18
+  }
19
+
20
+  return { type: head, bytes: Enc.base64ToBuf(lines.join('')) };
21
+};
22
+
23
+PEM.packBlock = function (opts) {
24
+  return '-----BEGIN ' + opts.type + '-----\n'
25
+    + Enc.bufToBase64(opts.bytes).match(/.{1,64}/g).join('\n') + '\n'
26
+    + '-----END ' + opts.type + '-----'
27
+  ;
28
+};

+ 204
- 0
lib/rasha.js View File

@@ -0,0 +1,204 @@
1
+'use strict';
2
+
3
+var RSA = module.exports;
4
+var SSH = require('./ssh.js');
5
+var PEM = require('./pem.js');
6
+var x509 = require('./x509.js');
7
+var ASN1 = require('./asn1.js');
8
+
9
+/*global Promise*/
10
+RSA.generate = function (opts) {
11
+  return Promise.resolve().then(function () {
12
+    var typ = 'rsa';
13
+    var format = opts.format;
14
+    var encoding = opts.encoding;
15
+    var priv;
16
+    var pub;
17
+
18
+    if (!format) {
19
+      format = 'jwk';
20
+    }
21
+    if ('spki' === format || 'pkcs8' === format) {
22
+      format = 'pkcs8';
23
+      pub = 'spki';
24
+    }
25
+
26
+    if ('pem' === format) {
27
+      format = 'pkcs1';
28
+      encoding = 'pem';
29
+    } else if ('der' === format) {
30
+      format = 'pkcs1';
31
+      encoding = 'der';
32
+    }
33
+
34
+    if ('jwk' === format || 'json' === format) {
35
+      format = 'jwk';
36
+      encoding = 'json';
37
+    } else {
38
+      priv = format;
39
+      pub = pub || format;
40
+    }
41
+
42
+    if (!encoding) {
43
+      encoding = 'pem';
44
+    }
45
+
46
+    if (priv) {
47
+      priv = { type: priv, format: encoding };
48
+      pub = { type: pub, format: encoding };
49
+    } else {
50
+      // jwk
51
+      priv = { type: 'pkcs1', format: 'pem' };
52
+      pub = { type: 'pkcs1', format: 'pem' };
53
+    }
54
+
55
+    return new Promise(function (resolve, reject) {
56
+      return require('crypto').generateKeyPair(typ, {
57
+        modulusLength: opts.modulusLength || 2048
58
+      , publicExponent: opts.publicExponent || 0x10001
59
+      , privateKeyEncoding: priv
60
+      , publicKeyEncoding: pub
61
+      }, function (err, pubkey, privkey) {
62
+        if (err) { reject(err); }
63
+        resolve({
64
+          private: privkey
65
+        , public: pubkey
66
+        });
67
+      });
68
+    }).then(function (keypair) {
69
+      if ('jwk' !== format) {
70
+        return keypair;
71
+      }
72
+
73
+      return {
74
+        private: RSA.importSync({ pem: keypair.private, format: priv.type })
75
+      , public: RSA.importSync({ pem: keypair.public, format: pub.type, public: true })
76
+      };
77
+    });
78
+  });
79
+};
80
+
81
+RSA.importSync = function (opts) {
82
+  if (!opts || !opts.pem || 'string' !== typeof opts.pem) {
83
+    throw new Error("must pass { pem: pem } as a string");
84
+  }
85
+
86
+  var jwk = { kty: 'RSA', n: null, e: null };
87
+  if (0 === opts.pem.indexOf('ssh-rsa ')) {
88
+    return SSH.parse(opts.pem, jwk);
89
+  }
90
+  var pem = opts.pem;
91
+  var block = PEM.parseBlock(pem);
92
+  //var hex = toHex(u8);
93
+  var asn1 = ASN1.parse(block.bytes);
94
+
95
+  var meta = x509.guess(block.bytes, asn1);
96
+
97
+  if ('pkcs1' === meta.format) {
98
+    jwk = x509.parsePkcs1(block.bytes, asn1, jwk);
99
+  } else {
100
+    jwk = x509.parsePkcs8(block.bytes, asn1, jwk);
101
+  }
102
+
103
+  if (opts.public) {
104
+    jwk = RSA.nueter(jwk);
105
+  }
106
+  return jwk;
107
+};
108
+RSA.parse = function parseRsa(opts) {
109
+  // wrapped in a promise for API compatibility
110
+  // with the forthcoming browser version
111
+  // (and potential future native node capability)
112
+  return Promise.resolve().then(function () {
113
+    return RSA.importSync(opts);
114
+  });
115
+};
116
+RSA.toJwk = RSA.import = RSA.parse;
117
+
118
+/*
119
+RSAPrivateKey ::= SEQUENCE {
120
+  version           Version,
121
+  modulus           INTEGER,  -- n
122
+  publicExponent    INTEGER,  -- e
123
+  privateExponent   INTEGER,  -- d
124
+  prime1            INTEGER,  -- p
125
+  prime2            INTEGER,  -- q
126
+  exponent1         INTEGER,  -- d mod (p-1)
127
+  exponent2         INTEGER,  -- d mod (q-1)
128
+  coefficient       INTEGER,  -- (inverse of q) mod p
129
+  otherPrimeInfos   OtherPrimeInfos OPTIONAL
130
+}
131
+*/
132
+
133
+RSA.exportSync = function (opts) {
134
+  if (!opts || !opts.jwk || 'object' !== typeof opts.jwk) {
135
+    throw new Error("must pass { jwk: jwk }");
136
+  }
137
+  var jwk = JSON.parse(JSON.stringify(opts.jwk));
138
+  var format = opts.format;
139
+  var pub = opts.public;
140
+  if (pub || -1 !== [ 'spki', 'pkix', 'ssh', 'rfc4716' ].indexOf(format)) {
141
+    jwk = RSA.nueter(jwk);
142
+  }
143
+  if ('RSA' !== jwk.kty) {
144
+    throw new Error("options.jwk.kty must be 'RSA' for RSA keys");
145
+  }
146
+  if (!jwk.p) {
147
+    // TODO test for n and e
148
+    pub = true;
149
+    if (!format || 'pkcs1' === format) {
150
+      format = 'pkcs1';
151
+    } else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
152
+      format = 'spki';
153
+    } else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
154
+      format = 'ssh';
155
+    } else {
156
+      throw new Error("options.format must be 'spki', 'pkcs1', or 'ssh' for public RSA keys, not ("
157
+        + typeof format + ") " + format);
158
+    }
159
+  } else {
160
+    // TODO test for all necessary keys (d, p, q ...)
161
+    if (!format || 'pkcs1' === format) {
162
+      format = 'pkcs1';
163
+    } else if ('pkcs8' !== format) {
164
+      throw new Error("options.format must be 'pkcs1' or 'pkcs8' for private RSA keys");
165
+    }
166
+  }
167
+
168
+  if ('pkcs1' === format) {
169
+    if (jwk.d) {
170
+      return PEM.packBlock({ type: "RSA PRIVATE KEY", bytes: x509.packPkcs1(jwk) });
171
+    } else {
172
+      return PEM.packBlock({ type: "RSA PUBLIC KEY", bytes: x509.packPkcs1(jwk) });
173
+    }
174
+  } else if ('pkcs8' === format) {
175
+    return PEM.packBlock({ type: "PRIVATE KEY", bytes: x509.packPkcs8(jwk) });
176
+  } else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
177
+    return PEM.packBlock({ type: "PUBLIC KEY", bytes: x509.packSpki(jwk) });
178
+  } else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
179
+    return SSH.pack({ jwk: jwk, comment: opts.comment });
180
+  } else {
181
+    throw new Error("Sanity Error: reached unreachable code block with format: " + format);
182
+  }
183
+};
184
+RSA.pack = function (opts) {
185
+  // wrapped in a promise for API compatibility
186
+  // with the forthcoming browser version
187
+  // (and potential future native node capability)
188
+  return Promise.resolve().then(function () {
189
+    return RSA.exportSync(opts);
190
+  });
191
+};
192
+RSA.toPem = RSA.export = RSA.pack;
193
+
194
+// snip the _private_ parts... hAHAHAHA!
195
+RSA.nueter = function (jwk) {
196
+  // (snip rather than new object to keep potential extra data)
197
+  // otherwise we could just do this:
198
+  // return { kty: jwk.kty, n: jwk.n, e: jwk.e };
199
+  [ 'p', 'q', 'd', 'dp', 'dq', 'qi' ].forEach(function (key) {
200
+    if (key in jwk) { jwk[key] = undefined; }
201
+    return jwk;
202
+  });
203
+  return jwk;
204
+};

+ 80
- 0
lib/ssh.js View File

@@ -0,0 +1,80 @@
1
+'use strict';
2
+
3
+var SSH = module.exports;
4
+var Enc = require('./encoding.js');
5
+
6
+              //  7  s  s  h  -  r  s  a
7
+SSH.RSA = '00000007 73 73 68 2d 72 73 61'.replace(/\s+/g, '').toLowerCase();
8
+
9
+SSH.parse = function (pem, jwk) {
10
+
11
+  var parts = pem.split(/\s+/);
12
+  var buf = Enc.base64ToBuf(parts[1]);
13
+  var els = [];
14
+  var index = 0;
15
+  var len;
16
+  var i = 0;
17
+  var offset = (buf.byteOffset || 0);
18
+  // using dataview to be browser-compatible (I do want _some_ code reuse)
19
+  var dv = new DataView(buf.buffer.slice(offset, offset + buf.byteLength));
20
+  var el;
21
+
22
+  if (SSH.RSA !== Enc.bufToHex(buf.slice(0, SSH.RSA.length/2))) {
23
+    throw new Error("does not lead with ssh header");
24
+  }
25
+
26
+  while (index < buf.byteLength) {
27
+    i += 1;
28
+    if (i > 3) { throw new Error("15+ elements, probably not a public ssh key"); }
29
+    len = dv.getUint32(index, false);
30
+    index += 4;
31
+    el = buf.slice(index, index + len);
32
+    // remove BigUInt '00' prefix
33
+    if (0x00 === el[0]) {
34
+      el = el.slice(1);
35
+    }
36
+    els.push(el);
37
+    index += len;
38
+  }
39
+
40
+  jwk.n = Enc.bufToUrlBase64(els[2]);
41
+  jwk.e = Enc.bufToUrlBase64(els[1]);
42
+
43
+  return jwk;
44
+};
45
+
46
+SSH.pack = function (opts) {
47
+  var jwk = opts.jwk;
48
+  var header = 'ssh-rsa';
49
+  var comment = opts.comment || 'rsa@localhost';
50
+  var e = SSH._padHexInt(Enc.base64ToHex(jwk.e));
51
+  var n = SSH._padHexInt(Enc.base64ToHex(jwk.n));
52
+  var hex = [
53
+    SSH._numToUint32Hex(header.length)
54
+  , Enc.strToHex(header)
55
+  , SSH._numToUint32Hex(e.length/2)
56
+  , e
57
+  , SSH._numToUint32Hex(n.length/2)
58
+  , n
59
+  ].join('');
60
+  return [ header, Enc.hexToBase64(hex), comment ].join(' ');
61
+};
62
+
63
+SSH._numToUint32Hex = function (num) {
64
+  var hex = num.toString(16);
65
+  while (hex.length < 8) {
66
+    hex = '0' + hex;
67
+  }
68
+  return hex;
69
+};
70
+
71
+SSH._padHexInt = function (hex) {
72
+  // BigInt is negative if the high order bit 0x80 is set,
73
+  // so ASN1, SSH, and many other formats pad with '0x00'
74
+  // to signifiy a positive number.
75
+  var i = parseInt(hex.slice(0, 2), 16);
76
+  if (0x80 & i) {
77
+    return '00' + hex;
78
+  }
79
+  return hex;
80
+};

+ 111
- 0
lib/telemetry.js View File

@@ -0,0 +1,111 @@
1
+'use strict';
2
+
3
+// We believe in a proactive approach to sustainable open source.
4
+// As part of that we make it easy for you to opt-in to following our progress
5
+// and we also stay up-to-date on telemetry such as operating system and node
6
+// version so that we can focus our efforts where they'll have the greatest impact.
7
+//
8
+// Want to learn more about our Terms, Privacy Policy, and Mission?
9
+// Check out https://therootcompany.com/legal/
10
+
11
+var os = require('os');
12
+var crypto = require('crypto');
13
+var https = require('https');
14
+var pkg = require('../package.json');
15
+
16
+// to help focus our efforts in the right places
17
+var data = {
18
+  package: pkg.name
19
+, version: pkg.version
20
+, node: process.version
21
+, arch: process.arch || os.arch()
22
+, platform: process.platform || os.platform()
23
+, release: os.release()
24
+};
25
+
26
+function addCommunityMember(opts) {
27
+  setTimeout(function () {
28
+    var req = https.request({
29
+      hostname: 'api.therootcompany.com'
30
+    , port: 443
31
+    , path: '/api/therootcompany.com/public/community'
32
+    , method: 'POST'
33
+    , headers: { 'Content-Type': 'application/json' }
34
+    }, function (resp) {
35
+      // let the data flow, so we can ignore it
36
+      resp.on('data', function () {});
37
+      //resp.on('data', function (chunk) { console.log(chunk.toString()); });
38
+      resp.on('error', function () { /*ignore*/ });
39
+      //resp.on('error', function (err) { console.error(err); });
40
+    });
41
+    var obj = JSON.parse(JSON.stringify(data));
42
+    obj.action = 'updates';
43
+    try {
44
+      obj.ppid = ppid(obj.action);
45
+    } catch(e) {
46
+      // ignore
47
+      //console.error(e);
48
+    }
49
+    obj.name = opts.name || undefined;
50
+    obj.address = opts.email;
51
+    obj.community = 'node.js@therootcompany.com';
52
+
53
+    req.write(JSON.stringify(obj, 2, null));
54
+    req.end();
55
+    req.on('error', function () { /*ignore*/ });
56
+    //req.on('error', function (err) { console.error(err); });
57
+  }, 50);
58
+}
59
+
60
+function ping(action) {
61
+  setTimeout(function () {
62
+    var req = https.request({
63
+      hostname: 'api.therootcompany.com'
64
+    , port: 443
65
+    , path: '/api/therootcompany.com/public/ping'
66
+    , method: 'POST'
67
+    , headers: { 'Content-Type': 'application/json' }
68
+    }, function (resp) {
69
+      // let the data flow, so we can ignore it
70
+      resp.on('data', function () { });
71
+      //resp.on('data', function (chunk) { console.log(chunk.toString()); });
72
+      resp.on('error', function () { /*ignore*/ });
73
+      //resp.on('error', function (err) { console.error(err); });
74
+    });
75
+    var obj = JSON.parse(JSON.stringify(data));
76
+    obj.action = action;
77
+    try {
78
+      obj.ppid = ppid(obj.action);
79
+    } catch(e) {
80
+      // ignore
81
+      //console.error(e);
82
+    }
83
+
84
+    req.write(JSON.stringify(obj, 2, null));
85
+    req.end();
86
+    req.on('error', function (/*e*/) { /*console.error('req.error', e);*/ });
87
+  }, 50);
88
+}
89
+
90
+// to help identify unique installs without getting
91
+// the personally identifiable info that we don't want
92
+function ppid(action) {
93
+  var parts = [ action, data.package, data.version, data.node, data.arch, data.platform, data.release ];
94
+  var ifaces = os.networkInterfaces();
95
+  Object.keys(ifaces).forEach(function (ifname) {
96
+    if (/^en/.test(ifname) || /^eth/.test(ifname) || /^wl/.test(ifname)) {
97
+      if  (ifaces[ifname] && ifaces[ifname].length) {
98
+        parts.push(ifaces[ifname][0].mac);
99
+      }
100
+    }
101
+  });
102
+  return crypto.createHash('sha1').update(parts.join(',')).digest('base64');
103
+}
104
+
105
+module.exports.ping = ping;
106
+module.exports.joinCommunity = addCommunityMember;
107
+
108
+if (require.main === module) {
109
+  ping('install');
110
+  //addCommunityMember({ name: "AJ ONeal", email: 'coolaj86@gmail.com' });
111
+}

+ 153
- 0
lib/x509.js View File

@@ -0,0 +1,153 @@
1
+'use strict';
2
+
3
+var x509 = module.exports;
4
+var ASN1 = require('./asn1.js');
5
+var Enc = require('./encoding.js');
6
+
7
+x509.guess = function (der, asn1) {
8
+  // accepting der for compatability with other usages
9
+
10
+  var meta = { kty: 'RSA', format: 'pkcs1', public: true };
11
+  //meta.asn1 = ASN1.parse(u8);
12
+
13
+  if (asn1.children.every(function(el) {
14
+    return 0x02 === el.type;
15
+  })) {
16
+    if (2 === asn1.children.length) {
17
+      // rsa pkcs1 public
18
+      return meta;
19
+    } else if (asn1.children.length >= 9) {
20
+      // the standard allows for "otherPrimeInfos", hence at least 9
21
+      meta.public = false;
22
+      // rsa pkcs1 private
23
+      return meta;
24
+    } else {
25
+      throw new Error("not an RSA PKCS#1 public or private key (wrong number of ints)");
26
+    }
27
+  } else {
28
+    meta.format = 'pkcs8';
29
+  }
30
+
31
+  return meta;
32
+};
33
+
34
+x509.parsePkcs1 = function parseRsaPkcs1(buf, asn1, jwk) {
35
+  if (!asn1.children.every(function(el) {
36
+    return 0x02 === el.type;
37
+  })) {
38
+    throw new Error("not an RSA PKCS#1 public or private key (not all ints)");
39
+  }
40
+
41
+  if (2 === asn1.children.length) {
42
+
43
+    jwk.n = Enc.bufToUrlBase64(asn1.children[0].value);
44
+    jwk.e = Enc.bufToUrlBase64(asn1.children[1].value);
45
+    return jwk;
46
+
47
+  } else if (asn1.children.length >= 9) {
48
+    // the standard allows for "otherPrimeInfos", hence at least 9
49
+
50
+    jwk.n = Enc.bufToUrlBase64(asn1.children[1].value);
51
+    jwk.e = Enc.bufToUrlBase64(asn1.children[2].value);
52
+    jwk.d = Enc.bufToUrlBase64(asn1.children[3].value);
53
+    jwk.p = Enc.bufToUrlBase64(asn1.children[4].value);
54
+    jwk.q = Enc.bufToUrlBase64(asn1.children[5].value);
55
+    jwk.dp = Enc.bufToUrlBase64(asn1.children[6].value);
56
+    jwk.dq = Enc.bufToUrlBase64(asn1.children[7].value);
57
+    jwk.qi = Enc.bufToUrlBase64(asn1.children[8].value);
58
+    return jwk;
59
+
60
+  } else {
61
+    throw new Error("not an RSA PKCS#1 public or private key (wrong number of ints)");
62
+  }
63
+};
64
+
65
+x509.parsePkcs8 = function parseRsaPkcs8(buf, asn1, jwk) {
66
+  if (2 === asn1.children.length
67
+    && 0x03 === asn1.children[1].type
68
+    && 0x30 === asn1.children[1].value[0]) {
69
+
70
+    asn1 = ASN1.parse(asn1.children[1].value);
71
+    jwk.n = Enc.bufToUrlBase64(asn1.children[0].value);
72
+    jwk.e = Enc.bufToUrlBase64(asn1.children[1].value);
73
+
74
+  } else if (3 === asn1.children.length
75
+    && 0x04 === asn1.children[2].type
76
+    && 0x30 === asn1.children[2].children[0].type
77
+    && 0x02 === asn1.children[2].children[0].children[0].type) {
78
+
79
+    asn1 = asn1.children[2].children[0];
80
+    jwk.n = Enc.bufToUrlBase64(asn1.children[1].value);
81
+    jwk.e = Enc.bufToUrlBase64(asn1.children[2].value);
82
+    jwk.d = Enc.bufToUrlBase64(asn1.children[3].value);
83
+    jwk.p = Enc.bufToUrlBase64(asn1.children[4].value);
84
+    jwk.q = Enc.bufToUrlBase64(asn1.children[5].value);
85
+    jwk.dp = Enc.bufToUrlBase64(asn1.children[6].value);
86
+    jwk.dq = Enc.bufToUrlBase64(asn1.children[7].value);
87
+    jwk.qi = Enc.bufToUrlBase64(asn1.children[8].value);
88
+
89
+  } else {
90
+    throw new Error("not an RSA PKCS#8 public or private key (wrong format)");
91
+  }
92
+  return jwk;
93
+};
94
+
95
+x509.packPkcs1 = function (jwk) {
96
+  var n = ASN1.UInt(Enc.base64ToHex(jwk.n));
97
+  var e = ASN1.UInt(Enc.base64ToHex(jwk.e));
98
+
99
+  if (!jwk.d) {
100
+    return Enc.hexToBuf(ASN1('30', n, e));
101
+  }
102
+
103
+  return Enc.hexToBuf(ASN1('30'
104
+  , ASN1.UInt('00')
105
+  , n
106
+  , e
107
+  , ASN1.UInt(Enc.base64ToHex(jwk.d))
108
+  , ASN1.UInt(Enc.base64ToHex(jwk.p))
109
+  , ASN1.UInt(Enc.base64ToHex(jwk.q))
110
+  , ASN1.UInt(Enc.base64ToHex(jwk.dp))
111
+  , ASN1.UInt(Enc.base64ToHex(jwk.dq))
112
+  , ASN1.UInt(Enc.base64ToHex(jwk.qi))
113
+  ));
114
+};
115
+
116
+x509.packPkcs8 = function (jwk) {
117
+  if (!jwk.d) {
118
+    // Public RSA
119
+    return Enc.hexToBuf(ASN1('30'
120
+      , ASN1('30'
121
+        , ASN1('06', '2a864886f70d010101')
122
+        , ASN1('05')
123
+      )
124
+      , ASN1.BitStr(ASN1('30'
125
+        , ASN1.UInt(Enc.base64ToHex(jwk.n))
126
+        , ASN1.UInt(Enc.base64ToHex(jwk.e))
127
+      ))
128
+    ));
129
+  }
130
+
131
+  // Private RSA
132
+  return Enc.hexToBuf(ASN1('30'
133
+    , ASN1.UInt('00')
134
+    , ASN1('30'
135
+      , ASN1('06', '2a864886f70d010101')
136
+      , ASN1('05')
137
+    )
138
+    , ASN1('04'
139
+      , ASN1('30'
140
+        , ASN1.UInt('00')
141
+        , ASN1.UInt(Enc.base64ToHex(jwk.n))
142
+        , ASN1.UInt(Enc.base64ToHex(jwk.e))
143
+        , ASN1.UInt(Enc.base64ToHex(jwk.d))
144
+        , ASN1.UInt(Enc.base64ToHex(jwk.p))
145
+        , ASN1.UInt(Enc.base64ToHex(jwk.q))
146
+        , ASN1.UInt(Enc.base64ToHex(jwk.dp))
147
+        , ASN1.UInt(Enc.base64ToHex(jwk.dq))
148
+        , ASN1.UInt(Enc.base64ToHex(jwk.qi))
149
+      )
150
+    )
151
+  ));
152
+};
153
+x509.packSpki = x509.packPkcs8;

+ 1
- 1
package.json View File

@@ -1,6 +1,6 @@
1 1
 {
2 2
   "name": "keypairs",
3
-  "version": "0.0.3",
3
+  "version": "0.0.4",
4 4
   "description": "Interchangeably use RSA & ECDSA with PEM and JWK for Signing, Verifying, CSR generation and JOSE. Ugh... that was a mouthful.",
5 5
   "main": "index.js",
6 6
   "scripts": {

Loading…
Cancel
Save