make Prettier
This commit is contained in:
parent
87a12c36b0
commit
6c11446e2f
|
@ -1,3 +1,4 @@
|
||||||
|
dist/
|
||||||
*.gz
|
*.gz
|
||||||
.*.sw*
|
.*.sw*
|
||||||
.ignore
|
.ignore
|
||||||
|
|
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"bracketSpacing": true,
|
||||||
|
"printWidth": 80,
|
||||||
|
"singleQuote": true,
|
||||||
|
"tabWidth": 4,
|
||||||
|
"trailingComma": "none",
|
||||||
|
"useTabs": true
|
||||||
|
}
|
|
@ -0,0 +1,60 @@
|
||||||
|
#!/usr/bin/env node
|
||||||
|
(async function() {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
var UglifyJS = require('uglify-js');
|
||||||
|
var path = require('path');
|
||||||
|
var fs = require('fs');
|
||||||
|
var promisify = require('util').promisify;
|
||||||
|
var readFile = promisify(fs.readFile);
|
||||||
|
var writeFile = promisify(fs.writeFile);
|
||||||
|
var gzip = promisify(require('zlib').gzip);
|
||||||
|
|
||||||
|
// The order is specific, and it matters
|
||||||
|
var files = await Promise.all(
|
||||||
|
[
|
||||||
|
'../lib/encoding.js',
|
||||||
|
'../lib/asn1-packer.js',
|
||||||
|
'../lib/x509.js',
|
||||||
|
'../lib/ecdsa.js',
|
||||||
|
'../lib/rsa.js',
|
||||||
|
'../lib/keypairs.js',
|
||||||
|
'../lib/asn1-parser.js',
|
||||||
|
'../lib/csr.js',
|
||||||
|
'../lib/acme.js'
|
||||||
|
].map(async function(file) {
|
||||||
|
return (await readFile(path.join(__dirname, file), 'utf8')).trim();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
var header =
|
||||||
|
[
|
||||||
|
'// Copyright 2015-2019 AJ ONeal. All rights reserved',
|
||||||
|
'/* This Source Code Form is subject to the terms of the Mozilla Public',
|
||||||
|
' * License, v. 2.0. If a copy of the MPL was not distributed with this',
|
||||||
|
' * file, You can obtain one at http://mozilla.org/MPL/2.0/. */'
|
||||||
|
].join('\n') + '\n';
|
||||||
|
|
||||||
|
var file = header + files.join('\n') + '\n';
|
||||||
|
await writeFile(path.join(__dirname, '../dist', 'acme.js'), file);
|
||||||
|
await writeFile(
|
||||||
|
path.join(__dirname, '../dist', 'acme.js.gz'),
|
||||||
|
await gzip(file)
|
||||||
|
);
|
||||||
|
|
||||||
|
// TODO source maps?
|
||||||
|
var result = UglifyJS.minify(file, {
|
||||||
|
compress: true,
|
||||||
|
// mangling doesn't save significant
|
||||||
|
mangle: false
|
||||||
|
});
|
||||||
|
if (result.error) {
|
||||||
|
throw result.error;
|
||||||
|
}
|
||||||
|
file = header + result.code;
|
||||||
|
await writeFile(path.join(__dirname, '../dist', 'acme.min.js'), file);
|
||||||
|
await writeFile(
|
||||||
|
path.join(__dirname, '../dist', 'acme.min.js.gz'),
|
||||||
|
await gzip(file)
|
||||||
|
);
|
||||||
|
})();
|
1306
lib/acme.js
1306
lib/acme.js
File diff suppressed because it is too large
Load Diff
|
@ -1,31 +1,40 @@
|
||||||
;(function (exports) {
|
(function(exports) {
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
if (!exports.ASN1) { exports.ASN1 = {}; }
|
if (!exports.ASN1) {
|
||||||
if (!exports.Enc) { exports.Enc = {}; }
|
exports.ASN1 = {};
|
||||||
if (!exports.PEM) { exports.PEM = {}; }
|
}
|
||||||
|
if (!exports.Enc) {
|
||||||
|
exports.Enc = {};
|
||||||
|
}
|
||||||
|
if (!exports.PEM) {
|
||||||
|
exports.PEM = {};
|
||||||
|
}
|
||||||
|
|
||||||
var ASN1 = exports.ASN1;
|
var ASN1 = exports.ASN1;
|
||||||
var Enc = exports.Enc;
|
var Enc = exports.Enc;
|
||||||
var PEM = exports.PEM;
|
var PEM = exports.PEM;
|
||||||
|
|
||||||
//
|
//
|
||||||
// Packer
|
// Packer
|
||||||
//
|
//
|
||||||
|
|
||||||
// Almost every ASN.1 type that's important for CSR
|
// Almost every ASN.1 type that's important for CSR
|
||||||
// can be represented generically with only a few rules.
|
// can be represented generically with only a few rules.
|
||||||
exports.ASN1 = function ASN1(/*type, hexstrings...*/) {
|
exports.ASN1 = function ASN1(/*type, hexstrings...*/) {
|
||||||
var args = Array.prototype.slice.call(arguments);
|
var args = Array.prototype.slice.call(arguments);
|
||||||
var typ = args.shift();
|
var typ = args.shift();
|
||||||
var str = args.join('').replace(/\s+/g, '').toLowerCase();
|
var str = args
|
||||||
var len = (str.length/2);
|
.join('')
|
||||||
|
.replace(/\s+/g, '')
|
||||||
|
.toLowerCase();
|
||||||
|
var len = str.length / 2;
|
||||||
var lenlen = 0;
|
var lenlen = 0;
|
||||||
var hex = typ;
|
var hex = typ;
|
||||||
|
|
||||||
// We can't have an odd number of hex chars
|
// We can't have an odd number of hex chars
|
||||||
if (len !== Math.round(len)) {
|
if (len !== Math.round(len)) {
|
||||||
throw new Error("invalid hex");
|
throw new Error('invalid hex');
|
||||||
}
|
}
|
||||||
|
|
||||||
// The first byte of any ASN.1 sequence is the type (Sequence, Integer, etc)
|
// The first byte of any ASN.1 sequence is the type (Sequence, Integer, etc)
|
||||||
|
@ -44,40 +53,44 @@ exports.ASN1 = function ASN1(/*type, hexstrings...*/) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (lenlen) { hex += Enc.numToHex(0x80 + lenlen); }
|
if (lenlen) {
|
||||||
return hex + Enc.numToHex(str.length/2) + str;
|
hex += Enc.numToHex(0x80 + lenlen);
|
||||||
};
|
}
|
||||||
|
return hex + Enc.numToHex(str.length / 2) + str;
|
||||||
|
};
|
||||||
|
|
||||||
// The Integer type has some special rules
|
// The Integer type has some special rules
|
||||||
ASN1.UInt = function UINT() {
|
ASN1.UInt = function UINT() {
|
||||||
var str = Array.prototype.slice.call(arguments).join('');
|
var str = Array.prototype.slice.call(arguments).join('');
|
||||||
var first = parseInt(str.slice(0, 2), 16);
|
var first = parseInt(str.slice(0, 2), 16);
|
||||||
|
|
||||||
// If the first byte is 0x80 or greater, the number is considered negative
|
// If the first byte is 0x80 or greater, the number is considered negative
|
||||||
// Therefore we add a '00' prefix if the 0x80 bit is set
|
// Therefore we add a '00' prefix if the 0x80 bit is set
|
||||||
if (0x80 & first) { str = '00' + str; }
|
if (0x80 & first) {
|
||||||
|
str = '00' + str;
|
||||||
|
}
|
||||||
|
|
||||||
return ASN1('02', str);
|
return ASN1('02', str);
|
||||||
};
|
};
|
||||||
|
|
||||||
// The Bit String type also has a special rule
|
// The Bit String type also has a special rule
|
||||||
ASN1.BitStr = function BITSTR() {
|
ASN1.BitStr = function BITSTR() {
|
||||||
var str = Array.prototype.slice.call(arguments).join('');
|
var str = Array.prototype.slice.call(arguments).join('');
|
||||||
// '00' is a mask of how many bits of the next byte to ignore
|
// '00' is a mask of how many bits of the next byte to ignore
|
||||||
return ASN1('03', '00' + str);
|
return ASN1('03', '00' + str);
|
||||||
};
|
};
|
||||||
|
|
||||||
ASN1.pack = function (arr) {
|
ASN1.pack = function(arr) {
|
||||||
var typ = Enc.numToHex(arr[0]);
|
var typ = Enc.numToHex(arr[0]);
|
||||||
var str = '';
|
var str = '';
|
||||||
if (Array.isArray(arr[1])) {
|
if (Array.isArray(arr[1])) {
|
||||||
arr[1].forEach(function (a) {
|
arr[1].forEach(function(a) {
|
||||||
str += ASN1.pack(a);
|
str += ASN1.pack(a);
|
||||||
});
|
});
|
||||||
} else if ('string' === typeof arr[1]) {
|
} else if ('string' === typeof arr[1]) {
|
||||||
str = arr[1];
|
str = arr[1];
|
||||||
} else {
|
} else {
|
||||||
throw new Error("unexpected array");
|
throw new Error('unexpected array');
|
||||||
}
|
}
|
||||||
if ('03' === typ) {
|
if ('03' === typ) {
|
||||||
return ASN1.BitStr(str);
|
return ASN1.BitStr(str);
|
||||||
|
@ -86,42 +99,49 @@ ASN1.pack = function (arr) {
|
||||||
} else {
|
} else {
|
||||||
return ASN1(typ, str);
|
return ASN1(typ, str);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Object.keys(ASN1).forEach(function (k) {
|
Object.keys(ASN1).forEach(function(k) {
|
||||||
exports.ASN1[k] = ASN1[k];
|
exports.ASN1[k] = ASN1[k];
|
||||||
});
|
});
|
||||||
ASN1 = exports.ASN1;
|
ASN1 = exports.ASN1;
|
||||||
|
|
||||||
PEM.packBlock = function (opts) {
|
PEM.packBlock = function(opts) {
|
||||||
// TODO allow for headers?
|
// TODO allow for headers?
|
||||||
return '-----BEGIN ' + opts.type + '-----\n'
|
return (
|
||||||
+ Enc.bufToBase64(opts.bytes).match(/.{1,64}/g).join('\n') + '\n'
|
'-----BEGIN ' +
|
||||||
+ '-----END ' + opts.type + '-----'
|
opts.type +
|
||||||
;
|
'-----\n' +
|
||||||
};
|
Enc.bufToBase64(opts.bytes)
|
||||||
|
.match(/.{1,64}/g)
|
||||||
|
.join('\n') +
|
||||||
|
'\n' +
|
||||||
|
'-----END ' +
|
||||||
|
opts.type +
|
||||||
|
'-----'
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
Enc.bufToBase64 = function (u8) {
|
Enc.bufToBase64 = function(u8) {
|
||||||
var bin = '';
|
var bin = '';
|
||||||
u8.forEach(function (i) {
|
u8.forEach(function(i) {
|
||||||
bin += String.fromCharCode(i);
|
bin += String.fromCharCode(i);
|
||||||
});
|
});
|
||||||
return btoa(bin);
|
return btoa(bin);
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.hexToBuf = function (hex) {
|
Enc.hexToBuf = function(hex) {
|
||||||
var arr = [];
|
var arr = [];
|
||||||
hex.match(/.{2}/g).forEach(function (h) {
|
hex.match(/.{2}/g).forEach(function(h) {
|
||||||
arr.push(parseInt(h, 16));
|
arr.push(parseInt(h, 16));
|
||||||
});
|
});
|
||||||
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.numToHex = function (d) {
|
Enc.numToHex = function(d) {
|
||||||
d = d.toString(16);
|
d = d.toString(16);
|
||||||
if (d.length % 2) {
|
if (d.length % 2) {
|
||||||
return '0' + d;
|
return '0' + d;
|
||||||
}
|
}
|
||||||
return d;
|
return d;
|
||||||
};
|
};
|
||||||
|
})('undefined' !== typeof window ? window : module.exports);
|
||||||
}('undefined' !== typeof window ? window : module.exports));
|
|
||||||
|
|
|
@ -2,38 +2,52 @@
|
||||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||||
;(function (exports) {
|
(function(exports) {
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
if (!exports.ASN1) { exports.ASN1 = {}; }
|
if (!exports.ASN1) {
|
||||||
if (!exports.Enc) { exports.Enc = {}; }
|
exports.ASN1 = {};
|
||||||
if (!exports.PEM) { exports.PEM = {}; }
|
}
|
||||||
|
if (!exports.Enc) {
|
||||||
|
exports.Enc = {};
|
||||||
|
}
|
||||||
|
if (!exports.PEM) {
|
||||||
|
exports.PEM = {};
|
||||||
|
}
|
||||||
|
|
||||||
var ASN1 = exports.ASN1;
|
var ASN1 = exports.ASN1;
|
||||||
var Enc = exports.Enc;
|
var Enc = exports.Enc;
|
||||||
var PEM = exports.PEM;
|
var PEM = exports.PEM;
|
||||||
|
|
||||||
//
|
//
|
||||||
// Parser
|
// Parser
|
||||||
//
|
//
|
||||||
|
|
||||||
// Although I've only seen 9 max in https certificates themselves,
|
// Although I've only seen 9 max in https certificates themselves,
|
||||||
// but each domain list could have up to 100
|
// but each domain list could have up to 100
|
||||||
ASN1.ELOOPN = 102;
|
ASN1.ELOOPN = 102;
|
||||||
ASN1.ELOOP = "uASN1.js Error: iterated over " + ASN1.ELOOPN + "+ elements (probably a malformed file)";
|
ASN1.ELOOP =
|
||||||
// I've seen https certificates go 29 deep
|
'uASN1.js Error: iterated over ' +
|
||||||
ASN1.EDEEPN = 60;
|
ASN1.ELOOPN +
|
||||||
ASN1.EDEEP = "uASN1.js Error: element nested " + ASN1.EDEEPN + "+ layers deep (probably a malformed file)";
|
'+ elements (probably a malformed file)';
|
||||||
// Container Types are Sequence 0x30, Container Array? (0xA0, 0xA1)
|
// I've seen https certificates go 29 deep
|
||||||
// Value Types are Boolean 0x01, Integer 0x02, Null 0x05, Object ID 0x06, String 0x0C, 0x16, 0x13, 0x1e Value Array? (0x82)
|
ASN1.EDEEPN = 60;
|
||||||
// Bit String (0x03) and Octet String (0x04) may be values or containers
|
ASN1.EDEEP =
|
||||||
// Sometimes Bit String is used as a container (RSA Pub Spki)
|
'uASN1.js Error: element nested ' +
|
||||||
ASN1.CTYPES = [ 0x30, 0x31, 0xa0, 0xa1 ];
|
ASN1.EDEEPN +
|
||||||
ASN1.VTYPES = [ 0x01, 0x02, 0x05, 0x06, 0x0c, 0x82 ];
|
'+ layers deep (probably a malformed file)';
|
||||||
ASN1.parse = function parseAsn1Helper(buf) {
|
// Container Types are Sequence 0x30, Container Array? (0xA0, 0xA1)
|
||||||
|
// Value Types are Boolean 0x01, Integer 0x02, Null 0x05, Object ID 0x06, String 0x0C, 0x16, 0x13, 0x1e Value Array? (0x82)
|
||||||
|
// Bit String (0x03) and Octet String (0x04) may be values or containers
|
||||||
|
// Sometimes Bit String is used as a container (RSA Pub Spki)
|
||||||
|
ASN1.CTYPES = [0x30, 0x31, 0xa0, 0xa1];
|
||||||
|
ASN1.VTYPES = [0x01, 0x02, 0x05, 0x06, 0x0c, 0x82];
|
||||||
|
ASN1.parse = function parseAsn1Helper(buf) {
|
||||||
//var ws = ' ';
|
//var ws = ' ';
|
||||||
function parseAsn1(buf, depth, eager) {
|
function parseAsn1(buf, depth, eager) {
|
||||||
if (depth.length >= ASN1.EDEEPN) { throw new Error(ASN1.EDEEP); }
|
if (depth.length >= ASN1.EDEEPN) {
|
||||||
|
throw new Error(ASN1.EDEEP);
|
||||||
|
}
|
||||||
|
|
||||||
var index = 2; // we know, at minimum, data starts after type (0) and lengthSize (1)
|
var index = 2; // we know, at minimum, data starts after type (0) and lengthSize (1)
|
||||||
var asn1 = { type: buf[0], lengthSize: 0, length: buf[1] };
|
var asn1 = { type: buf[0], lengthSize: 0, length: buf[1] };
|
||||||
|
@ -46,13 +60,19 @@ ASN1.parse = function parseAsn1Helper(buf) {
|
||||||
if (0x80 & asn1.length) {
|
if (0x80 & asn1.length) {
|
||||||
asn1.lengthSize = 0x7f & asn1.length;
|
asn1.lengthSize = 0x7f & asn1.length;
|
||||||
// I think that buf->hex->int solves the problem of Endianness... not sure
|
// I think that buf->hex->int solves the problem of Endianness... not sure
|
||||||
asn1.length = parseInt(Enc.bufToHex(buf.slice(index, index + asn1.lengthSize)), 16);
|
asn1.length = parseInt(
|
||||||
|
Enc.bufToHex(buf.slice(index, index + asn1.lengthSize)),
|
||||||
|
16
|
||||||
|
);
|
||||||
index += asn1.lengthSize;
|
index += asn1.lengthSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
// High-order bit Integers have a leading 0x00 to signify that they are positive.
|
// High-order bit Integers have a leading 0x00 to signify that they are positive.
|
||||||
// Bit Streams use the first byte to signify padding, which x.509 doesn't use.
|
// Bit Streams use the first byte to signify padding, which x.509 doesn't use.
|
||||||
if (0x00 === buf[index] && (0x02 === asn1.type || 0x03 === asn1.type)) {
|
if (
|
||||||
|
0x00 === buf[index] &&
|
||||||
|
(0x02 === asn1.type || 0x03 === asn1.type)
|
||||||
|
) {
|
||||||
// However, 0x00 on its own is a valid number
|
// However, 0x00 on its own is a valid number
|
||||||
if (asn1.length > 1) {
|
if (asn1.length > 1) {
|
||||||
index += 1;
|
index += 1;
|
||||||
|
@ -66,96 +86,137 @@ ASN1.parse = function parseAsn1Helper(buf) {
|
||||||
function parseChildren(eager) {
|
function parseChildren(eager) {
|
||||||
asn1.children = [];
|
asn1.children = [];
|
||||||
//console.warn('1 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', 0);
|
//console.warn('1 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', 0);
|
||||||
while (iters < ASN1.ELOOPN && index < (2 + asn1.length + asn1.lengthSize)) {
|
while (
|
||||||
|
iters < ASN1.ELOOPN &&
|
||||||
|
index < 2 + asn1.length + asn1.lengthSize
|
||||||
|
) {
|
||||||
iters += 1;
|
iters += 1;
|
||||||
depth.length += 1;
|
depth.length += 1;
|
||||||
child = parseAsn1(buf.slice(index, index + adjustedLen), depth, eager);
|
child = parseAsn1(
|
||||||
|
buf.slice(index, index + adjustedLen),
|
||||||
|
depth,
|
||||||
|
eager
|
||||||
|
);
|
||||||
depth.length -= 1;
|
depth.length -= 1;
|
||||||
// The numbers don't match up exactly and I don't remember why...
|
// The numbers don't match up exactly and I don't remember why...
|
||||||
// probably something with adjustedLen or some such, but the tests pass
|
// probably something with adjustedLen or some such, but the tests pass
|
||||||
index += (2 + child.lengthSize + child.length);
|
index += 2 + child.lengthSize + child.length;
|
||||||
//console.warn('2 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', (2 + child.lengthSize + child.length));
|
//console.warn('2 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', (2 + child.lengthSize + child.length));
|
||||||
if (index > (2 + asn1.lengthSize + asn1.length)) {
|
if (index > 2 + asn1.lengthSize + asn1.length) {
|
||||||
if (!eager) { console.error(JSON.stringify(asn1, ASN1._replacer, 2)); }
|
if (!eager) {
|
||||||
throw new Error("Parse error: child value length (" + child.length
|
console.error(
|
||||||
+ ") is greater than remaining parent length (" + (asn1.length - index)
|
JSON.stringify(asn1, ASN1._replacer, 2)
|
||||||
+ " = " + asn1.length + " - " + index + ")");
|
);
|
||||||
|
}
|
||||||
|
throw new Error(
|
||||||
|
'Parse error: child value length (' +
|
||||||
|
child.length +
|
||||||
|
') is greater than remaining parent length (' +
|
||||||
|
(asn1.length - index) +
|
||||||
|
' = ' +
|
||||||
|
asn1.length +
|
||||||
|
' - ' +
|
||||||
|
index +
|
||||||
|
')'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
asn1.children.push(child);
|
asn1.children.push(child);
|
||||||
//console.warn(depth.join(ws) + '0x' + Enc.numToHex(asn1.type), index, 'len:', asn1.length, asn1);
|
//console.warn(depth.join(ws) + '0x' + Enc.numToHex(asn1.type), index, 'len:', asn1.length, asn1);
|
||||||
}
|
}
|
||||||
if (index !== (2 + asn1.lengthSize + asn1.length)) {
|
if (index !== 2 + asn1.lengthSize + asn1.length) {
|
||||||
//console.warn('index:', index, 'length:', (2 + asn1.lengthSize + asn1.length));
|
//console.warn('index:', index, 'length:', (2 + asn1.lengthSize + asn1.length));
|
||||||
throw new Error("premature end-of-file");
|
throw new Error('premature end-of-file');
|
||||||
|
}
|
||||||
|
if (iters >= ASN1.ELOOPN) {
|
||||||
|
throw new Error(ASN1.ELOOP);
|
||||||
}
|
}
|
||||||
if (iters >= ASN1.ELOOPN) { throw new Error(ASN1.ELOOP); }
|
|
||||||
|
|
||||||
delete asn1.value;
|
delete asn1.value;
|
||||||
return asn1;
|
return asn1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recurse into types that are _always_ containers
|
// Recurse into types that are _always_ containers
|
||||||
if (-1 !== ASN1.CTYPES.indexOf(asn1.type)) { return parseChildren(eager); }
|
if (-1 !== ASN1.CTYPES.indexOf(asn1.type)) {
|
||||||
|
return parseChildren(eager);
|
||||||
|
}
|
||||||
|
|
||||||
// Return types that are _always_ values
|
// Return types that are _always_ values
|
||||||
asn1.value = buf.slice(index, index + adjustedLen);
|
asn1.value = buf.slice(index, index + adjustedLen);
|
||||||
if (-1 !== ASN1.VTYPES.indexOf(asn1.type)) { return asn1; }
|
if (-1 !== ASN1.VTYPES.indexOf(asn1.type)) {
|
||||||
|
return asn1;
|
||||||
|
}
|
||||||
|
|
||||||
// For ambigious / unknown types, recurse and return on failure
|
// For ambigious / unknown types, recurse and return on failure
|
||||||
// (and return child array size to zero)
|
// (and return child array size to zero)
|
||||||
try { return parseChildren(true); }
|
try {
|
||||||
catch(e) { asn1.children.length = 0; return asn1; }
|
return parseChildren(true);
|
||||||
|
} catch (e) {
|
||||||
|
asn1.children.length = 0;
|
||||||
|
return asn1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var asn1 = parseAsn1(buf, []);
|
var asn1 = parseAsn1(buf, []);
|
||||||
var len = buf.byteLength || buf.length;
|
var len = buf.byteLength || buf.length;
|
||||||
if (len !== 2 + asn1.lengthSize + asn1.length) {
|
if (len !== 2 + asn1.lengthSize + asn1.length) {
|
||||||
throw new Error("Length of buffer does not match length of ASN.1 sequence.");
|
throw new Error(
|
||||||
|
'Length of buffer does not match length of ASN.1 sequence.'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return asn1;
|
return asn1;
|
||||||
};
|
};
|
||||||
ASN1._replacer = function (k, v) {
|
ASN1._replacer = function(k, v) {
|
||||||
if ('type' === k) { return '0x' + Enc.numToHex(v); }
|
if ('type' === k) {
|
||||||
if (v && 'value' === k) { return '0x' + Enc.bufToHex(v.data || v); }
|
return '0x' + Enc.numToHex(v);
|
||||||
|
}
|
||||||
|
if (v && 'value' === k) {
|
||||||
|
return '0x' + Enc.bufToHex(v.data || v);
|
||||||
|
}
|
||||||
return v;
|
return v;
|
||||||
};
|
};
|
||||||
|
|
||||||
// don't replace the full parseBlock, if it exists
|
// don't replace the full parseBlock, if it exists
|
||||||
PEM.parseBlock = PEM.parseBlock || function (str) {
|
PEM.parseBlock =
|
||||||
var der = str.split(/\n/).filter(function (line) {
|
PEM.parseBlock ||
|
||||||
|
function(str) {
|
||||||
|
var der = str
|
||||||
|
.split(/\n/)
|
||||||
|
.filter(function(line) {
|
||||||
return !/-----/.test(line);
|
return !/-----/.test(line);
|
||||||
}).join('');
|
})
|
||||||
|
.join('');
|
||||||
return { bytes: Enc.base64ToBuf(der) };
|
return { bytes: Enc.base64ToBuf(der) };
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.base64ToBuf = function (b64) {
|
Enc.base64ToBuf = function(b64) {
|
||||||
return Enc.binToBuf(atob(b64));
|
return Enc.binToBuf(atob(b64));
|
||||||
};
|
};
|
||||||
Enc.binToBuf = function (bin) {
|
Enc.binToBuf = function(bin) {
|
||||||
var arr = bin.split('').map(function (ch) {
|
var arr = bin.split('').map(function(ch) {
|
||||||
return ch.charCodeAt(0);
|
return ch.charCodeAt(0);
|
||||||
});
|
});
|
||||||
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
||||||
};
|
};
|
||||||
Enc.bufToHex = function (u8) {
|
Enc.bufToHex = function(u8) {
|
||||||
var hex = [];
|
var hex = [];
|
||||||
var i, h;
|
var i, h;
|
||||||
var len = (u8.byteLength || u8.length);
|
var len = u8.byteLength || u8.length;
|
||||||
|
|
||||||
for (i = 0; i < len; i += 1) {
|
for (i = 0; i < len; i += 1) {
|
||||||
h = u8[i].toString(16);
|
h = u8[i].toString(16);
|
||||||
if (h.length % 2) { h = '0' + h; }
|
if (h.length % 2) {
|
||||||
|
h = '0' + h;
|
||||||
|
}
|
||||||
hex.push(h);
|
hex.push(h);
|
||||||
}
|
}
|
||||||
|
|
||||||
return hex.join('').toLowerCase();
|
return hex.join('').toLowerCase();
|
||||||
};
|
};
|
||||||
Enc.numToHex = function (d) {
|
Enc.numToHex = function(d) {
|
||||||
d = d.toString(16);
|
d = d.toString(16);
|
||||||
if (d.length % 2) {
|
if (d.length % 2) {
|
||||||
return '0' + d;
|
return '0' + d;
|
||||||
}
|
}
|
||||||
return d;
|
return d;
|
||||||
};
|
};
|
||||||
|
})('undefined' !== typeof window ? window : module.exports);
|
||||||
}('undefined' !== typeof window ? window : module.exports));
|
|
||||||
|
|
332
lib/csr.js
332
lib/csr.js
|
@ -2,94 +2,108 @@
|
||||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||||
(function (exports) {
|
(function(exports) {
|
||||||
'use strict';
|
'use strict';
|
||||||
/*global Promise*/
|
/*global Promise*/
|
||||||
|
|
||||||
var ASN1 = exports.ASN1;
|
var ASN1 = exports.ASN1;
|
||||||
var Enc = exports.Enc;
|
var Enc = exports.Enc;
|
||||||
var PEM = exports.PEM;
|
var PEM = exports.PEM;
|
||||||
var X509 = exports.x509;
|
var X509 = exports.x509;
|
||||||
var Keypairs = exports.Keypairs;
|
var Keypairs = exports.Keypairs;
|
||||||
|
|
||||||
// TODO find a way that the prior node-ish way of `module.exports = function () {}` isn't broken
|
// TODO find a way that the prior node-ish way of `module.exports = function () {}` isn't broken
|
||||||
var CSR = exports.CSR = function (opts) {
|
var CSR = (exports.CSR = function(opts) {
|
||||||
// We're using a Promise here to be compatible with the browser version
|
// We're using a Promise here to be compatible with the browser version
|
||||||
// which will probably use the webcrypto API for some of the conversions
|
// which will probably use the webcrypto API for some of the conversions
|
||||||
return CSR._prepare(opts).then(function (opts) {
|
return CSR._prepare(opts).then(function(opts) {
|
||||||
return CSR.create(opts).then(function (bytes) {
|
return CSR.create(opts).then(function(bytes) {
|
||||||
return CSR._encode(opts, bytes);
|
return CSR._encode(opts, bytes);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
});
|
||||||
|
|
||||||
CSR._prepare = function (opts) {
|
CSR._prepare = function(opts) {
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
var Keypairs;
|
var Keypairs;
|
||||||
opts = JSON.parse(JSON.stringify(opts));
|
opts = JSON.parse(JSON.stringify(opts));
|
||||||
|
|
||||||
// We do a bit of extra error checking for user convenience
|
// We do a bit of extra error checking for user convenience
|
||||||
if (!opts) { throw new Error("You must pass options with key and domains to rsacsr"); }
|
if (!opts) {
|
||||||
|
throw new Error(
|
||||||
|
'You must pass options with key and domains to rsacsr'
|
||||||
|
);
|
||||||
|
}
|
||||||
if (!Array.isArray(opts.domains) || 0 === opts.domains.length) {
|
if (!Array.isArray(opts.domains) || 0 === opts.domains.length) {
|
||||||
new Error("You must pass options.domains as a non-empty array");
|
new Error('You must pass options.domains as a non-empty array');
|
||||||
}
|
}
|
||||||
|
|
||||||
// I need to check that 例.中国 is a valid domain name
|
// I need to check that 例.中国 is a valid domain name
|
||||||
if (!opts.domains.every(function (d) {
|
if (
|
||||||
|
!opts.domains.every(function(d) {
|
||||||
// allow punycode? xn--
|
// allow punycode? xn--
|
||||||
if ('string' === typeof d /*&& /\./.test(d) && !/--/.test(d)*/) {
|
if (
|
||||||
|
'string' ===
|
||||||
|
typeof d /*&& /\./.test(d) && !/--/.test(d)*/
|
||||||
|
) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
})) {
|
})
|
||||||
throw new Error("You must pass options.domains as strings");
|
) {
|
||||||
|
throw new Error('You must pass options.domains as strings');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opts.jwk) { return opts; }
|
if (opts.jwk) {
|
||||||
|
return opts;
|
||||||
|
}
|
||||||
if (opts.key && opts.key.kty) {
|
if (opts.key && opts.key.kty) {
|
||||||
opts.jwk = opts.key;
|
opts.jwk = opts.key;
|
||||||
return opts;
|
return opts;
|
||||||
}
|
}
|
||||||
if (!opts.pem && !opts.key) {
|
if (!opts.pem && !opts.key) {
|
||||||
throw new Error("You must pass options.key as a JSON web key");
|
throw new Error('You must pass options.key as a JSON web key');
|
||||||
}
|
}
|
||||||
|
|
||||||
Keypairs = exports.Keypairs;
|
Keypairs = exports.Keypairs;
|
||||||
if (!exports.Keypairs) {
|
if (!exports.Keypairs) {
|
||||||
throw new Error("Keypairs.js is an optional dependency for PEM-to-JWK.\n"
|
throw new Error(
|
||||||
+ "Install it if you'd like to use it:\n"
|
'Keypairs.js is an optional dependency for PEM-to-JWK.\n' +
|
||||||
+ "\tnpm install --save rasha\n"
|
"Install it if you'd like to use it:\n" +
|
||||||
+ "Otherwise supply a jwk as the private key."
|
'\tnpm install --save rasha\n' +
|
||||||
|
'Otherwise supply a jwk as the private key.'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Keypairs.import({ pem: opts.pem || opts.key }).then(function (pair) {
|
return Keypairs.import({ pem: opts.pem || opts.key }).then(function(
|
||||||
|
pair
|
||||||
|
) {
|
||||||
opts.jwk = pair.private;
|
opts.jwk = pair.private;
|
||||||
return opts;
|
return opts;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
CSR._encode = function (opts, bytes) {
|
CSR._encode = function(opts, bytes) {
|
||||||
if ('der' === (opts.encoding||'').toLowerCase()) {
|
if ('der' === (opts.encoding || '').toLowerCase()) {
|
||||||
return bytes;
|
return bytes;
|
||||||
}
|
}
|
||||||
return PEM.packBlock({
|
return PEM.packBlock({
|
||||||
type: "CERTIFICATE REQUEST"
|
type: 'CERTIFICATE REQUEST',
|
||||||
, bytes: bytes /* { jwk: jwk, domains: opts.domains } */
|
bytes: bytes /* { jwk: jwk, domains: opts.domains } */
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
CSR.create = function createCsr(opts) {
|
CSR.create = function createCsr(opts) {
|
||||||
var hex = CSR.request(opts.jwk, opts.domains);
|
var hex = CSR.request(opts.jwk, opts.domains);
|
||||||
return CSR._sign(opts.jwk, hex).then(function (csr) {
|
return CSR._sign(opts.jwk, hex).then(function(csr) {
|
||||||
return Enc.hexToBuf(csr);
|
return Enc.hexToBuf(csr);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
//
|
//
|
||||||
// EC / RSA
|
// EC / RSA
|
||||||
//
|
//
|
||||||
CSR.request = function createCsrBodyEc(jwk, domains) {
|
CSR.request = function createCsrBodyEc(jwk, domains) {
|
||||||
var asn1pub;
|
var asn1pub;
|
||||||
if (/^EC/i.test(jwk.kty)) {
|
if (/^EC/i.test(jwk.kty)) {
|
||||||
asn1pub = X509.packCsrEcPublicKey(jwk);
|
asn1pub = X509.packCsrEcPublicKey(jwk);
|
||||||
|
@ -97,18 +111,25 @@ CSR.request = function createCsrBodyEc(jwk, domains) {
|
||||||
asn1pub = X509.packCsrRsaPublicKey(jwk);
|
asn1pub = X509.packCsrRsaPublicKey(jwk);
|
||||||
}
|
}
|
||||||
return X509.packCsr(asn1pub, domains);
|
return X509.packCsr(asn1pub, domains);
|
||||||
};
|
};
|
||||||
|
|
||||||
CSR._sign = function csrEcSig(jwk, request) {
|
CSR._sign = function csrEcSig(jwk, request) {
|
||||||
// Took some tips from https://gist.github.com/codermapuche/da4f96cdb6d5ff53b7ebc156ec46a10a
|
// Took some tips from https://gist.github.com/codermapuche/da4f96cdb6d5ff53b7ebc156ec46a10a
|
||||||
// TODO will have to convert web ECDSA signatures to PEM ECDSA signatures (but RSA should be the same)
|
// TODO will have to convert web ECDSA signatures to PEM ECDSA signatures (but RSA should be the same)
|
||||||
// TODO have a consistent non-private way to sign
|
// TODO have a consistent non-private way to sign
|
||||||
return Keypairs._sign({ jwk: jwk, format: 'x509' }, Enc.hexToBuf(request)).then(function (sig) {
|
return Keypairs._sign(
|
||||||
return CSR._toDer({ request: request, signature: sig, kty: jwk.kty });
|
{ jwk: jwk, format: 'x509' },
|
||||||
|
Enc.hexToBuf(request)
|
||||||
|
).then(function(sig) {
|
||||||
|
return CSR._toDer({
|
||||||
|
request: request,
|
||||||
|
signature: sig,
|
||||||
|
kty: jwk.kty
|
||||||
});
|
});
|
||||||
};
|
});
|
||||||
|
};
|
||||||
|
|
||||||
CSR._toDer = function encode(opts) {
|
CSR._toDer = function encode(opts) {
|
||||||
var sty;
|
var sty;
|
||||||
if (/^EC/i.test(opts.kty)) {
|
if (/^EC/i.test(opts.kty)) {
|
||||||
// 1.2.840.10045.4.3.2 ecdsaWithSHA256 (ANSI X9.62 ECDSA algorithm with SHA256)
|
// 1.2.840.10045.4.3.2 ecdsaWithSHA256 (ANSI X9.62 ECDSA algorithm with SHA256)
|
||||||
|
@ -117,47 +138,79 @@ CSR._toDer = function encode(opts) {
|
||||||
// 1.2.840.113549.1.1.11 sha256WithRSAEncryption (PKCS #1)
|
// 1.2.840.113549.1.1.11 sha256WithRSAEncryption (PKCS #1)
|
||||||
sty = ASN1('30', ASN1('06', '2a864886f70d01010b'), ASN1('05'));
|
sty = ASN1('30', ASN1('06', '2a864886f70d01010b'), ASN1('05'));
|
||||||
}
|
}
|
||||||
return ASN1('30'
|
return ASN1(
|
||||||
|
'30',
|
||||||
// The Full CSR Request Body
|
// The Full CSR Request Body
|
||||||
, opts.request
|
opts.request,
|
||||||
// The Signature Type
|
// The Signature Type
|
||||||
, sty
|
sty,
|
||||||
// The Signature
|
// The Signature
|
||||||
, ASN1.BitStr(Enc.bufToHex(opts.signature))
|
ASN1.BitStr(Enc.bufToHex(opts.signature))
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
X509.packCsr = function (asn1pubkey, domains) {
|
X509.packCsr = function(asn1pubkey, domains) {
|
||||||
return ASN1('30'
|
return ASN1(
|
||||||
|
'30',
|
||||||
// Version (0)
|
// Version (0)
|
||||||
, ASN1.UInt('00')
|
ASN1.UInt('00'),
|
||||||
|
|
||||||
// 2.5.4.3 commonName (X.520 DN component)
|
// 2.5.4.3 commonName (X.520 DN component)
|
||||||
, ASN1('30', ASN1('31', ASN1('30', ASN1('06', '550403'), ASN1('0c', Enc.utf8ToHex(domains[0])))))
|
ASN1(
|
||||||
|
'30',
|
||||||
|
ASN1(
|
||||||
|
'31',
|
||||||
|
ASN1(
|
||||||
|
'30',
|
||||||
|
ASN1('06', '550403'),
|
||||||
|
ASN1('0c', Enc.utf8ToHex(domains[0]))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
),
|
||||||
|
|
||||||
// Public Key (RSA or EC)
|
// Public Key (RSA or EC)
|
||||||
, asn1pubkey
|
asn1pubkey,
|
||||||
|
|
||||||
// Request Body
|
// Request Body
|
||||||
, ASN1('a0'
|
ASN1(
|
||||||
, ASN1('30'
|
'a0',
|
||||||
|
ASN1(
|
||||||
|
'30',
|
||||||
// 1.2.840.113549.1.9.14 extensionRequest (PKCS #9 via CRMF)
|
// 1.2.840.113549.1.9.14 extensionRequest (PKCS #9 via CRMF)
|
||||||
, ASN1('06', '2a864886f70d01090e')
|
ASN1('06', '2a864886f70d01090e'),
|
||||||
, ASN1('31'
|
ASN1(
|
||||||
, ASN1('30'
|
'31',
|
||||||
, ASN1('30'
|
ASN1(
|
||||||
|
'30',
|
||||||
|
ASN1(
|
||||||
|
'30',
|
||||||
// 2.5.29.17 subjectAltName (X.509 extension)
|
// 2.5.29.17 subjectAltName (X.509 extension)
|
||||||
, ASN1('06', '551d11')
|
ASN1('06', '551d11'),
|
||||||
, ASN1('04'
|
ASN1(
|
||||||
, ASN1('30', domains.map(function (d) {
|
'04',
|
||||||
return ASN1('82', Enc.utf8ToHex(d));
|
ASN1(
|
||||||
}).join(''))))))))
|
'30',
|
||||||
|
domains
|
||||||
|
.map(function(d) {
|
||||||
|
return ASN1(
|
||||||
|
'82',
|
||||||
|
Enc.utf8ToHex(d)
|
||||||
);
|
);
|
||||||
};
|
})
|
||||||
|
.join('')
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
// TODO finish this later
|
// TODO finish this later
|
||||||
// we want to parse the domains, the public key, and verify the signature
|
// we want to parse the domains, the public key, and verify the signature
|
||||||
CSR._info = function (der) {
|
CSR._info = function(der) {
|
||||||
// standard base64 PEM
|
// standard base64 PEM
|
||||||
if ('string' === typeof der && '-' === der[0]) {
|
if ('string' === typeof der && '-' === der[0]) {
|
||||||
der = PEM.parseBlock(der).bytes;
|
der = PEM.parseBlock(der).bytes;
|
||||||
|
@ -171,13 +224,19 @@ CSR._info = function (der) {
|
||||||
var kty;
|
var kty;
|
||||||
// A cert has 3 parts: cert, signature meta, signature
|
// A cert has 3 parts: cert, signature meta, signature
|
||||||
if (c.children.length !== 3) {
|
if (c.children.length !== 3) {
|
||||||
throw new Error("doesn't look like a certificate request: expected 3 parts of header");
|
throw new Error(
|
||||||
|
"doesn't look like a certificate request: expected 3 parts of header"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
var sig = c.children[2];
|
var sig = c.children[2];
|
||||||
if (sig.children.length) {
|
if (sig.children.length) {
|
||||||
// ASN1/X509 EC
|
// ASN1/X509 EC
|
||||||
sig = sig.children[0];
|
sig = sig.children[0];
|
||||||
sig = ASN1('30', ASN1.UInt(Enc.bufToHex(sig.children[0].value)), ASN1.UInt(Enc.bufToHex(sig.children[1].value)));
|
sig = ASN1(
|
||||||
|
'30',
|
||||||
|
ASN1.UInt(Enc.bufToHex(sig.children[0].value)),
|
||||||
|
ASN1.UInt(Enc.bufToHex(sig.children[1].value))
|
||||||
|
);
|
||||||
sig = Enc.hexToBuf(sig);
|
sig = Enc.hexToBuf(sig);
|
||||||
kty = 'EC';
|
kty = 'EC';
|
||||||
} else {
|
} else {
|
||||||
|
@ -189,11 +248,15 @@ CSR._info = function (der) {
|
||||||
var req = c.children[0];
|
var req = c.children[0];
|
||||||
// TODO utf8
|
// TODO utf8
|
||||||
if (4 !== req.children.length) {
|
if (4 !== req.children.length) {
|
||||||
throw new Error("doesn't look like a certificate request: expected 4 parts to request");
|
throw new Error(
|
||||||
|
"doesn't look like a certificate request: expected 4 parts to request"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
// 0 null
|
// 0 null
|
||||||
// 1 commonName / subject
|
// 1 commonName / subject
|
||||||
var sub = Enc.bufToBin(req.children[1].children[0].children[0].children[1].value);
|
var sub = Enc.bufToBin(
|
||||||
|
req.children[1].children[0].children[0].children[1].value
|
||||||
|
);
|
||||||
// 3 public key (type, key)
|
// 3 public key (type, key)
|
||||||
//console.log('oid', Enc.bufToHex(req.children[2].children[0].children[0].value));
|
//console.log('oid', Enc.bufToHex(req.children[2].children[0].children[0].value));
|
||||||
var pub;
|
var pub;
|
||||||
|
@ -202,8 +265,12 @@ CSR._info = function (der) {
|
||||||
// throw away compression byte
|
// throw away compression byte
|
||||||
pub = req.children[2].children[1].value.slice(1);
|
pub = req.children[2].children[1].value.slice(1);
|
||||||
pub = { kty: kty, x: pub.slice(0, 32), y: pub.slice(32) };
|
pub = { kty: kty, x: pub.slice(0, 32), y: pub.slice(32) };
|
||||||
while (0 === pub.x[0]) { pub.x = pub.x.slice(1); }
|
while (0 === pub.x[0]) {
|
||||||
while (0 === pub.y[0]) { pub.y = pub.y.slice(1); }
|
pub.x = pub.x.slice(1);
|
||||||
|
}
|
||||||
|
while (0 === pub.y[0]) {
|
||||||
|
pub.y = pub.y.slice(1);
|
||||||
|
}
|
||||||
if ((pub.x.length || pub.x.byteLength) > 48) {
|
if ((pub.x.length || pub.x.byteLength) > 48) {
|
||||||
pub.crv = 'P-521';
|
pub.crv = 'P-521';
|
||||||
} else if ((pub.x.length || pub.x.byteLength) > 32) {
|
} else if ((pub.x.length || pub.x.byteLength) > 32) {
|
||||||
|
@ -215,84 +282,121 @@ CSR._info = function (der) {
|
||||||
pub.y = Enc.bufToUrlBase64(pub.y);
|
pub.y = Enc.bufToUrlBase64(pub.y);
|
||||||
} else {
|
} else {
|
||||||
pub = req.children[2].children[1].children[0];
|
pub = req.children[2].children[1].children[0];
|
||||||
pub = { kty: kty, n: pub.children[0].value, e: pub.children[1].value };
|
pub = {
|
||||||
while (0 === pub.n[0]) { pub.n = pub.n.slice(1); }
|
kty: kty,
|
||||||
while (0 === pub.e[0]) { pub.e = pub.e.slice(1); }
|
n: pub.children[0].value,
|
||||||
|
e: pub.children[1].value
|
||||||
|
};
|
||||||
|
while (0 === pub.n[0]) {
|
||||||
|
pub.n = pub.n.slice(1);
|
||||||
|
}
|
||||||
|
while (0 === pub.e[0]) {
|
||||||
|
pub.e = pub.e.slice(1);
|
||||||
|
}
|
||||||
pub.n = Enc.bufToUrlBase64(pub.n);
|
pub.n = Enc.bufToUrlBase64(pub.n);
|
||||||
pub.e = Enc.bufToUrlBase64(pub.e);
|
pub.e = Enc.bufToUrlBase64(pub.e);
|
||||||
}
|
}
|
||||||
// 4 extensions
|
// 4 extensions
|
||||||
var domains = req.children[3].children.filter(function (seq) {
|
var domains = req.children[3].children
|
||||||
|
.filter(function(seq) {
|
||||||
// 1.2.840.113549.1.9.14 extensionRequest (PKCS #9 via CRMF)
|
// 1.2.840.113549.1.9.14 extensionRequest (PKCS #9 via CRMF)
|
||||||
if ('2a864886f70d01090e' === Enc.bufToHex(seq.children[0].value)) {
|
if (
|
||||||
|
'2a864886f70d01090e' === Enc.bufToHex(seq.children[0].value)
|
||||||
|
) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}).map(function (seq) {
|
})
|
||||||
return seq.children[1].children[0].children.filter(function (seq2) {
|
.map(function(seq) {
|
||||||
|
return seq.children[1].children[0].children
|
||||||
|
.filter(function(seq2) {
|
||||||
// subjectAltName (X.509 extension)
|
// subjectAltName (X.509 extension)
|
||||||
if ('551d11' === Enc.bufToHex(seq2.children[0].value)) {
|
if ('551d11' === Enc.bufToHex(seq2.children[0].value)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}).map(function (seq2) {
|
})
|
||||||
return seq2.children[1].children[0].children.map(function (name) {
|
.map(function(seq2) {
|
||||||
|
return seq2.children[1].children[0].children.map(
|
||||||
|
function(name) {
|
||||||
// TODO utf8
|
// TODO utf8
|
||||||
return Enc.bufToBin(name.value);
|
return Enc.bufToBin(name.value);
|
||||||
});
|
}
|
||||||
|
);
|
||||||
})[0];
|
})[0];
|
||||||
})[0];
|
})[0];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
subject: sub
|
subject: sub,
|
||||||
, altnames: domains
|
altnames: domains,
|
||||||
, jwk: pub
|
jwk: pub,
|
||||||
, signature: sig
|
signature: sig
|
||||||
|
};
|
||||||
};
|
};
|
||||||
};
|
|
||||||
|
|
||||||
X509.packCsrRsaPublicKey = function (jwk) {
|
X509.packCsrRsaPublicKey = function(jwk) {
|
||||||
// Sequence the key
|
// Sequence the key
|
||||||
var n = ASN1.UInt(Enc.base64ToHex(jwk.n));
|
var n = ASN1.UInt(Enc.base64ToHex(jwk.n));
|
||||||
var e = ASN1.UInt(Enc.base64ToHex(jwk.e));
|
var e = ASN1.UInt(Enc.base64ToHex(jwk.e));
|
||||||
var asn1pub = ASN1('30', n, e);
|
var asn1pub = ASN1('30', n, e);
|
||||||
|
|
||||||
// Add the CSR pub key header
|
// Add the CSR pub key header
|
||||||
return ASN1('30', ASN1('30', ASN1('06', '2a864886f70d010101'), ASN1('05')), ASN1.BitStr(asn1pub));
|
return ASN1(
|
||||||
};
|
'30',
|
||||||
|
ASN1('30', ASN1('06', '2a864886f70d010101'), ASN1('05')),
|
||||||
|
ASN1.BitStr(asn1pub)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
X509.packCsrEcPublicKey = function (jwk) {
|
X509.packCsrEcPublicKey = function(jwk) {
|
||||||
var ecOid = X509._oids[jwk.crv];
|
var ecOid = X509._oids[jwk.crv];
|
||||||
if (!ecOid) {
|
if (!ecOid) {
|
||||||
throw new Error("Unsupported namedCurve '" + jwk.crv + "'. Supported types are " + Object.keys(X509._oids));
|
throw new Error(
|
||||||
|
"Unsupported namedCurve '" +
|
||||||
|
jwk.crv +
|
||||||
|
"'. Supported types are " +
|
||||||
|
Object.keys(X509._oids)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
var cmp = '04'; // 04 == x+y, 02 == x-only
|
var cmp = '04'; // 04 == x+y, 02 == x-only
|
||||||
var hxy = '';
|
var hxy = '';
|
||||||
// Placeholder. I'm not even sure if compression should be supported.
|
// Placeholder. I'm not even sure if compression should be supported.
|
||||||
if (!jwk.y) { cmp = '02'; }
|
if (!jwk.y) {
|
||||||
|
cmp = '02';
|
||||||
|
}
|
||||||
hxy += Enc.base64ToHex(jwk.x);
|
hxy += Enc.base64ToHex(jwk.x);
|
||||||
if (jwk.y) { hxy += Enc.base64ToHex(jwk.y); }
|
if (jwk.y) {
|
||||||
|
hxy += Enc.base64ToHex(jwk.y);
|
||||||
|
}
|
||||||
|
|
||||||
// 1.2.840.10045.2.1 ecPublicKey
|
// 1.2.840.10045.2.1 ecPublicKey
|
||||||
return ASN1('30', ASN1('30', ASN1('06', '2a8648ce3d0201'), ASN1('06', ecOid)), ASN1.BitStr(cmp + hxy));
|
return ASN1(
|
||||||
};
|
'30',
|
||||||
X509._oids = {
|
ASN1('30', ASN1('06', '2a8648ce3d0201'), ASN1('06', ecOid)),
|
||||||
|
ASN1.BitStr(cmp + hxy)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
X509._oids = {
|
||||||
// 1.2.840.10045.3.1.7 prime256v1
|
// 1.2.840.10045.3.1.7 prime256v1
|
||||||
// (ANSI X9.62 named elliptic curve) (06 08 - 2A 86 48 CE 3D 03 01 07)
|
// (ANSI X9.62 named elliptic curve) (06 08 - 2A 86 48 CE 3D 03 01 07)
|
||||||
'P-256': '2a8648ce3d030107'
|
'P-256': '2a8648ce3d030107',
|
||||||
// 1.3.132.0.34 P-384 (06 05 - 2B 81 04 00 22)
|
// 1.3.132.0.34 P-384 (06 05 - 2B 81 04 00 22)
|
||||||
// (SEC 2 recommended EC domain secp256r1)
|
// (SEC 2 recommended EC domain secp256r1)
|
||||||
, 'P-384': '2b81040022'
|
'P-384': '2b81040022'
|
||||||
// requires more logic and isn't a recommended standard
|
// requires more logic and isn't a recommended standard
|
||||||
// 1.3.132.0.35 P-521 (06 05 - 2B 81 04 00 23)
|
// 1.3.132.0.35 P-521 (06 05 - 2B 81 04 00 23)
|
||||||
// (SEC 2 alternate P-521)
|
// (SEC 2 alternate P-521)
|
||||||
//, 'P-521': '2B 81 04 00 23'
|
//, 'P-521': '2B 81 04 00 23'
|
||||||
};
|
};
|
||||||
|
|
||||||
// don't replace the full parseBlock, if it exists
|
// don't replace the full parseBlock, if it exists
|
||||||
PEM.parseBlock = PEM.parseBlock || function (str) {
|
PEM.parseBlock =
|
||||||
var der = str.split(/\n/).filter(function (line) {
|
PEM.parseBlock ||
|
||||||
|
function(str) {
|
||||||
|
var der = str
|
||||||
|
.split(/\n/)
|
||||||
|
.filter(function(line) {
|
||||||
return !/-----/.test(line);
|
return !/-----/.test(line);
|
||||||
}).join('');
|
})
|
||||||
|
.join('');
|
||||||
return { bytes: Enc.base64ToBuf(der) };
|
return { bytes: Enc.base64ToBuf(der) };
|
||||||
};
|
};
|
||||||
|
})('undefined' === typeof window ? module.exports : window);
|
||||||
}('undefined' === typeof window ? module.exports : window));
|
|
||||||
|
|
215
lib/ecdsa.js
215
lib/ecdsa.js
|
@ -1,22 +1,30 @@
|
||||||
/*global Promise*/
|
/*global Promise*/
|
||||||
(function (exports) {
|
(function(exports) {
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var EC = exports.Eckles = {};
|
var EC = (exports.Eckles = {});
|
||||||
var x509 = exports.x509;
|
var x509 = exports.x509;
|
||||||
if ('undefined' !== typeof module) { module.exports = EC; }
|
if ('undefined' !== typeof module) {
|
||||||
var PEM = exports.PEM;
|
module.exports = EC;
|
||||||
var SSH = exports.SSH;
|
}
|
||||||
var Enc = {};
|
var PEM = exports.PEM;
|
||||||
var textEncoder = new TextEncoder();
|
var SSH = exports.SSH;
|
||||||
|
var Enc = {};
|
||||||
|
var textEncoder = new TextEncoder();
|
||||||
|
|
||||||
EC._stance = "We take the stance that if you're knowledgeable enough to"
|
EC._stance =
|
||||||
+ " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway.";
|
"We take the stance that if you're knowledgeable enough to" +
|
||||||
EC._universal = "Bluecrypt only supports crypto with standard cross-browser and cross-platform support.";
|
" properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway.";
|
||||||
EC.generate = function (opts) {
|
EC._universal =
|
||||||
|
'Bluecrypt only supports crypto with standard cross-browser and cross-platform support.';
|
||||||
|
EC.generate = function(opts) {
|
||||||
var wcOpts = {};
|
var wcOpts = {};
|
||||||
if (!opts) { opts = {}; }
|
if (!opts) {
|
||||||
if (!opts.kty) { opts.kty = 'EC'; }
|
opts = {};
|
||||||
|
}
|
||||||
|
if (!opts.kty) {
|
||||||
|
opts.kty = 'EC';
|
||||||
|
}
|
||||||
|
|
||||||
// ECDSA has only the P curves and an associated bitlength
|
// ECDSA has only the P curves and an associated bitlength
|
||||||
wcOpts.name = 'ECDSA';
|
wcOpts.name = 'ECDSA';
|
||||||
|
@ -26,147 +34,194 @@ EC.generate = function (opts) {
|
||||||
wcOpts.namedCurve = opts.namedCurve; // true for supported curves
|
wcOpts.namedCurve = opts.namedCurve; // true for supported curves
|
||||||
if (/256/.test(wcOpts.namedCurve)) {
|
if (/256/.test(wcOpts.namedCurve)) {
|
||||||
wcOpts.namedCurve = 'P-256';
|
wcOpts.namedCurve = 'P-256';
|
||||||
wcOpts.hash = { name: "SHA-256" };
|
wcOpts.hash = { name: 'SHA-256' };
|
||||||
} else if (/384/.test(wcOpts.namedCurve)) {
|
} else if (/384/.test(wcOpts.namedCurve)) {
|
||||||
wcOpts.namedCurve = 'P-384';
|
wcOpts.namedCurve = 'P-384';
|
||||||
wcOpts.hash = { name: "SHA-384" };
|
wcOpts.hash = { name: 'SHA-384' };
|
||||||
} else {
|
} else {
|
||||||
return Promise.Reject(new Error("'" + wcOpts.namedCurve + "' is not an NIST approved ECDSA namedCurve. "
|
return Promise.Reject(
|
||||||
+ " Please choose either 'P-256' or 'P-384'. "
|
new Error(
|
||||||
+ EC._stance));
|
"'" +
|
||||||
|
wcOpts.namedCurve +
|
||||||
|
"' is not an NIST approved ECDSA namedCurve. " +
|
||||||
|
" Please choose either 'P-256' or 'P-384'. " +
|
||||||
|
EC._stance
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
var extractable = true;
|
var extractable = true;
|
||||||
return window.crypto.subtle.generateKey(
|
return window.crypto.subtle
|
||||||
wcOpts
|
.generateKey(wcOpts, extractable, ['sign', 'verify'])
|
||||||
, extractable
|
.then(function(result) {
|
||||||
, [ 'sign', 'verify' ]
|
return window.crypto.subtle
|
||||||
).then(function (result) {
|
.exportKey('jwk', result.privateKey)
|
||||||
return window.crypto.subtle.exportKey(
|
.then(function(privJwk) {
|
||||||
"jwk"
|
|
||||||
, result.privateKey
|
|
||||||
).then(function (privJwk) {
|
|
||||||
privJwk.key_ops = undefined;
|
privJwk.key_ops = undefined;
|
||||||
privJwk.ext = undefined;
|
privJwk.ext = undefined;
|
||||||
return {
|
return {
|
||||||
private: privJwk
|
private: privJwk,
|
||||||
, public: EC.neuter({ jwk: privJwk })
|
public: EC.neuter({ jwk: privJwk })
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
EC.export = function (opts) {
|
EC.export = function(opts) {
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
if (!opts || !opts.jwk || 'object' !== typeof opts.jwk) {
|
if (!opts || !opts.jwk || 'object' !== typeof opts.jwk) {
|
||||||
throw new Error("must pass { jwk: jwk } as a JSON object");
|
throw new Error('must pass { jwk: jwk } as a JSON object');
|
||||||
}
|
}
|
||||||
var jwk = JSON.parse(JSON.stringify(opts.jwk));
|
var jwk = JSON.parse(JSON.stringify(opts.jwk));
|
||||||
var format = opts.format;
|
var format = opts.format;
|
||||||
if (opts.public || -1 !== [ 'spki', 'pkix', 'ssh', 'rfc4716' ].indexOf(format)) {
|
if (
|
||||||
|
opts.public ||
|
||||||
|
-1 !== ['spki', 'pkix', 'ssh', 'rfc4716'].indexOf(format)
|
||||||
|
) {
|
||||||
jwk.d = null;
|
jwk.d = null;
|
||||||
}
|
}
|
||||||
if ('EC' !== jwk.kty) {
|
if ('EC' !== jwk.kty) {
|
||||||
throw new Error("options.jwk.kty must be 'EC' for EC keys");
|
throw new Error("options.jwk.kty must be 'EC' for EC keys");
|
||||||
}
|
}
|
||||||
if (!jwk.d) {
|
if (!jwk.d) {
|
||||||
if (!format || -1 !== [ 'spki', 'pkix' ].indexOf(format)) {
|
if (!format || -1 !== ['spki', 'pkix'].indexOf(format)) {
|
||||||
format = 'spki';
|
format = 'spki';
|
||||||
} else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
|
} else if (-1 !== ['ssh', 'rfc4716'].indexOf(format)) {
|
||||||
format = 'ssh';
|
format = 'ssh';
|
||||||
} else {
|
} else {
|
||||||
throw new Error("options.format must be 'spki' or 'ssh' for public EC keys, not ("
|
throw new Error(
|
||||||
+ typeof format + ") " + format);
|
"options.format must be 'spki' or 'ssh' for public EC keys, not (" +
|
||||||
|
typeof format +
|
||||||
|
') ' +
|
||||||
|
format
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!format || 'sec1' === format) {
|
if (!format || 'sec1' === format) {
|
||||||
format = 'sec1';
|
format = 'sec1';
|
||||||
} else if ('pkcs8' !== format) {
|
} else if ('pkcs8' !== format) {
|
||||||
throw new Error("options.format must be 'sec1' or 'pkcs8' for private EC keys, not '" + format + "'");
|
throw new Error(
|
||||||
|
"options.format must be 'sec1' or 'pkcs8' for private EC keys, not '" +
|
||||||
|
format +
|
||||||
|
"'"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (-1 === [ 'P-256', 'P-384' ].indexOf(jwk.crv)) {
|
if (-1 === ['P-256', 'P-384'].indexOf(jwk.crv)) {
|
||||||
throw new Error("options.jwk.crv must be either P-256 or P-384 for EC keys, not '" + jwk.crv + "'");
|
throw new Error(
|
||||||
|
"options.jwk.crv must be either P-256 or P-384 for EC keys, not '" +
|
||||||
|
jwk.crv +
|
||||||
|
"'"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (!jwk.y) {
|
if (!jwk.y) {
|
||||||
throw new Error("options.jwk.y must be a urlsafe base64-encoded either P-256 or P-384");
|
throw new Error(
|
||||||
|
'options.jwk.y must be a urlsafe base64-encoded either P-256 or P-384'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('sec1' === format) {
|
if ('sec1' === format) {
|
||||||
return PEM.packBlock({ type: "EC PRIVATE KEY", bytes: x509.packSec1(jwk) });
|
return PEM.packBlock({
|
||||||
|
type: 'EC PRIVATE KEY',
|
||||||
|
bytes: x509.packSec1(jwk)
|
||||||
|
});
|
||||||
} else if ('pkcs8' === format) {
|
} else if ('pkcs8' === format) {
|
||||||
return PEM.packBlock({ type: "PRIVATE KEY", bytes: x509.packPkcs8(jwk) });
|
return PEM.packBlock({
|
||||||
} else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
|
type: 'PRIVATE KEY',
|
||||||
return PEM.packBlock({ type: "PUBLIC KEY", bytes: x509.packSpki(jwk) });
|
bytes: x509.packPkcs8(jwk)
|
||||||
} else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
|
});
|
||||||
|
} else if (-1 !== ['spki', 'pkix'].indexOf(format)) {
|
||||||
|
return PEM.packBlock({
|
||||||
|
type: 'PUBLIC KEY',
|
||||||
|
bytes: x509.packSpki(jwk)
|
||||||
|
});
|
||||||
|
} else if (-1 !== ['ssh', 'rfc4716'].indexOf(format)) {
|
||||||
return SSH.packSsh(jwk);
|
return SSH.packSsh(jwk);
|
||||||
} else {
|
} else {
|
||||||
throw new Error("Sanity Error: reached unreachable code block with format: " + format);
|
throw new Error(
|
||||||
|
'Sanity Error: reached unreachable code block with format: ' +
|
||||||
|
format
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
EC.pack = function (opts) {
|
EC.pack = function(opts) {
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
return EC.exportSync(opts);
|
return EC.exportSync(opts);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Chopping off the private parts is now part of the public API.
|
// Chopping off the private parts is now part of the public API.
|
||||||
// I thought it sounded a little too crude at first, but it really is the best name in every possible way.
|
// I thought it sounded a little too crude at first, but it really is the best name in every possible way.
|
||||||
EC.neuter = function (opts) {
|
EC.neuter = function(opts) {
|
||||||
// trying to find the best balance of an immutable copy with custom attributes
|
// trying to find the best balance of an immutable copy with custom attributes
|
||||||
var jwk = {};
|
var jwk = {};
|
||||||
Object.keys(opts.jwk).forEach(function (k) {
|
Object.keys(opts.jwk).forEach(function(k) {
|
||||||
if ('undefined' === typeof opts.jwk[k]) { return; }
|
if ('undefined' === typeof opts.jwk[k]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
// ignore EC private parts
|
// ignore EC private parts
|
||||||
if ('d' === k) { return; }
|
if ('d' === k) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k]));
|
jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k]));
|
||||||
});
|
});
|
||||||
return jwk;
|
return jwk;
|
||||||
};
|
};
|
||||||
|
|
||||||
// https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk
|
// https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk
|
||||||
EC.__thumbprint = function (jwk) {
|
EC.__thumbprint = function(jwk) {
|
||||||
// Use the same entropy for SHA as for key
|
// Use the same entropy for SHA as for key
|
||||||
var alg = 'SHA-256';
|
var alg = 'SHA-256';
|
||||||
if (/384/.test(jwk.crv)) {
|
if (/384/.test(jwk.crv)) {
|
||||||
alg = 'SHA-384';
|
alg = 'SHA-384';
|
||||||
}
|
}
|
||||||
return window.crypto.subtle.digest(
|
return window.crypto.subtle
|
||||||
{ name: alg }
|
.digest(
|
||||||
, textEncoder.encode('{"crv":"' + jwk.crv + '","kty":"EC","x":"' + jwk.x + '","y":"' + jwk.y + '"}')
|
{ name: alg },
|
||||||
).then(function (hash) {
|
textEncoder.encode(
|
||||||
|
'{"crv":"' +
|
||||||
|
jwk.crv +
|
||||||
|
'","kty":"EC","x":"' +
|
||||||
|
jwk.x +
|
||||||
|
'","y":"' +
|
||||||
|
jwk.y +
|
||||||
|
'"}'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.then(function(hash) {
|
||||||
return Enc.bufToUrlBase64(new Uint8Array(hash));
|
return Enc.bufToUrlBase64(new Uint8Array(hash));
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
EC.thumbprint = function (opts) {
|
EC.thumbprint = function(opts) {
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
var jwk;
|
var jwk;
|
||||||
if ('EC' === opts.kty) {
|
if ('EC' === opts.kty) {
|
||||||
jwk = opts;
|
jwk = opts;
|
||||||
} else if (opts.jwk) {
|
} else if (opts.jwk) {
|
||||||
jwk = opts.jwk;
|
jwk = opts.jwk;
|
||||||
} else {
|
} else {
|
||||||
return EC.import(opts).then(function (jwk) {
|
return EC.import(opts).then(function(jwk) {
|
||||||
return EC.__thumbprint(jwk);
|
return EC.__thumbprint(jwk);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return EC.__thumbprint(jwk);
|
return EC.__thumbprint(jwk);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.bufToUrlBase64 = function (u8) {
|
Enc.bufToUrlBase64 = function(u8) {
|
||||||
return Enc.bufToBase64(u8)
|
return Enc.bufToBase64(u8)
|
||||||
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
|
.replace(/\+/g, '-')
|
||||||
};
|
.replace(/\//g, '_')
|
||||||
|
.replace(/=/g, '');
|
||||||
|
};
|
||||||
|
|
||||||
Enc.bufToBase64 = function (u8) {
|
Enc.bufToBase64 = function(u8) {
|
||||||
var bin = '';
|
var bin = '';
|
||||||
u8.forEach(function (i) {
|
u8.forEach(function(i) {
|
||||||
bin += String.fromCharCode(i);
|
bin += String.fromCharCode(i);
|
||||||
});
|
});
|
||||||
return btoa(bin);
|
return btoa(bin);
|
||||||
};
|
};
|
||||||
|
})('undefined' !== typeof module ? module.exports : window);
|
||||||
}('undefined' !== typeof module ? module.exports : window));
|
|
||||||
|
|
131
lib/encoding.js
131
lib/encoding.js
|
@ -1,31 +1,32 @@
|
||||||
(function (exports) {
|
(function(exports) {
|
||||||
|
var Enc = (exports.Enc = {});
|
||||||
|
|
||||||
var Enc = exports.Enc = {};
|
Enc.bufToBin = function(buf) {
|
||||||
|
|
||||||
Enc.bufToBin = function (buf) {
|
|
||||||
var bin = '';
|
var bin = '';
|
||||||
// cannot use .map() because Uint8Array would return only 0s
|
// cannot use .map() because Uint8Array would return only 0s
|
||||||
buf.forEach(function (ch) {
|
buf.forEach(function(ch) {
|
||||||
bin += String.fromCharCode(ch);
|
bin += String.fromCharCode(ch);
|
||||||
});
|
});
|
||||||
return bin;
|
return bin;
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.bufToHex = function toHex(u8) {
|
Enc.bufToHex = function toHex(u8) {
|
||||||
var hex = [];
|
var hex = [];
|
||||||
var i, h;
|
var i, h;
|
||||||
var len = (u8.byteLength || u8.length);
|
var len = u8.byteLength || u8.length;
|
||||||
|
|
||||||
for (i = 0; i < len; i += 1) {
|
for (i = 0; i < len; i += 1) {
|
||||||
h = u8[i].toString(16);
|
h = u8[i].toString(16);
|
||||||
if (h.length % 2) { h = '0' + h; }
|
if (h.length % 2) {
|
||||||
|
h = '0' + h;
|
||||||
|
}
|
||||||
hex.push(h);
|
hex.push(h);
|
||||||
}
|
}
|
||||||
|
|
||||||
return hex.join('').toLowerCase();
|
return hex.join('').toLowerCase();
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.urlBase64ToBase64 = function urlsafeBase64ToBase64(str) {
|
Enc.urlBase64ToBase64 = function urlsafeBase64ToBase64(str) {
|
||||||
var r = str % 4;
|
var r = str % 4;
|
||||||
if (2 === r) {
|
if (2 === r) {
|
||||||
str += '==';
|
str += '==';
|
||||||
|
@ -33,100 +34,112 @@ Enc.urlBase64ToBase64 = function urlsafeBase64ToBase64(str) {
|
||||||
str += '=';
|
str += '=';
|
||||||
}
|
}
|
||||||
return str.replace(/-/g, '+').replace(/_/g, '/');
|
return str.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.base64ToBuf = function (b64) {
|
Enc.base64ToBuf = function(b64) {
|
||||||
return Enc.binToBuf(atob(b64));
|
return Enc.binToBuf(atob(b64));
|
||||||
};
|
};
|
||||||
Enc.binToBuf = function (bin) {
|
Enc.binToBuf = function(bin) {
|
||||||
var arr = bin.split('').map(function (ch) {
|
var arr = bin.split('').map(function(ch) {
|
||||||
return ch.charCodeAt(0);
|
return ch.charCodeAt(0);
|
||||||
});
|
});
|
||||||
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
||||||
};
|
};
|
||||||
Enc.bufToHex = function (u8) {
|
Enc.bufToHex = function(u8) {
|
||||||
var hex = [];
|
var hex = [];
|
||||||
var i, h;
|
var i, h;
|
||||||
var len = (u8.byteLength || u8.length);
|
var len = u8.byteLength || u8.length;
|
||||||
|
|
||||||
for (i = 0; i < len; i += 1) {
|
for (i = 0; i < len; i += 1) {
|
||||||
h = u8[i].toString(16);
|
h = u8[i].toString(16);
|
||||||
if (h.length % 2) { h = '0' + h; }
|
if (h.length % 2) {
|
||||||
|
h = '0' + h;
|
||||||
|
}
|
||||||
hex.push(h);
|
hex.push(h);
|
||||||
}
|
}
|
||||||
|
|
||||||
return hex.join('').toLowerCase();
|
return hex.join('').toLowerCase();
|
||||||
};
|
};
|
||||||
Enc.numToHex = function (d) {
|
Enc.numToHex = function(d) {
|
||||||
d = d.toString(16);
|
d = d.toString(16);
|
||||||
if (d.length % 2) {
|
if (d.length % 2) {
|
||||||
return '0' + d;
|
return '0' + d;
|
||||||
}
|
}
|
||||||
return d;
|
return d;
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.bufToUrlBase64 = function (u8) {
|
Enc.bufToUrlBase64 = function(u8) {
|
||||||
return Enc.base64ToUrlBase64(Enc.bufToBase64(u8));
|
return Enc.base64ToUrlBase64(Enc.bufToBase64(u8));
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.base64ToUrlBase64 = function (str) {
|
Enc.base64ToUrlBase64 = function(str) {
|
||||||
return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
|
return str
|
||||||
};
|
.replace(/\+/g, '-')
|
||||||
|
.replace(/\//g, '_')
|
||||||
|
.replace(/=/g, '');
|
||||||
|
};
|
||||||
|
|
||||||
Enc.bufToBase64 = function (u8) {
|
Enc.bufToBase64 = function(u8) {
|
||||||
var bin = '';
|
var bin = '';
|
||||||
u8.forEach(function (i) {
|
u8.forEach(function(i) {
|
||||||
bin += String.fromCharCode(i);
|
bin += String.fromCharCode(i);
|
||||||
});
|
});
|
||||||
return btoa(bin);
|
return btoa(bin);
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.hexToBuf = function (hex) {
|
Enc.hexToBuf = function(hex) {
|
||||||
var arr = [];
|
var arr = [];
|
||||||
hex.match(/.{2}/g).forEach(function (h) {
|
hex.match(/.{2}/g).forEach(function(h) {
|
||||||
arr.push(parseInt(h, 16));
|
arr.push(parseInt(h, 16));
|
||||||
});
|
});
|
||||||
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.numToHex = function (d) {
|
Enc.numToHex = function(d) {
|
||||||
d = d.toString(16);
|
d = d.toString(16);
|
||||||
if (d.length % 2) {
|
if (d.length % 2) {
|
||||||
return '0' + d;
|
return '0' + d;
|
||||||
}
|
}
|
||||||
return d;
|
return d;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//
|
||||||
//
|
// JWK to SSH (tested working)
|
||||||
// JWK to SSH (tested working)
|
//
|
||||||
//
|
Enc.base64ToHex = function(b64) {
|
||||||
Enc.base64ToHex = function (b64) {
|
|
||||||
var bin = atob(Enc.urlBase64ToBase64(b64));
|
var bin = atob(Enc.urlBase64ToBase64(b64));
|
||||||
return Enc.binToHex(bin);
|
return Enc.binToHex(bin);
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.binToHex = function (bin) {
|
Enc.binToHex = function(bin) {
|
||||||
return bin.split('').map(function (ch) {
|
return bin
|
||||||
|
.split('')
|
||||||
|
.map(function(ch) {
|
||||||
var h = ch.charCodeAt(0).toString(16);
|
var h = ch.charCodeAt(0).toString(16);
|
||||||
if (h.length % 2) { h = '0' + h; }
|
if (h.length % 2) {
|
||||||
|
h = '0' + h;
|
||||||
|
}
|
||||||
return h;
|
return h;
|
||||||
}).join('');
|
})
|
||||||
};
|
.join('');
|
||||||
// TODO are there any nuance differences here?
|
};
|
||||||
Enc.utf8ToHex = Enc.binToHex;
|
// TODO are there any nuance differences here?
|
||||||
|
Enc.utf8ToHex = Enc.binToHex;
|
||||||
|
|
||||||
Enc.hexToBase64 = function (hex) {
|
Enc.hexToBase64 = function(hex) {
|
||||||
return btoa(Enc.hexToBin(hex));
|
return btoa(Enc.hexToBin(hex));
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.hexToBin = function (hex) {
|
Enc.hexToBin = function(hex) {
|
||||||
return hex.match(/.{2}/g).map(function (h) {
|
return hex
|
||||||
|
.match(/.{2}/g)
|
||||||
|
.map(function(h) {
|
||||||
return String.fromCharCode(parseInt(h, 16));
|
return String.fromCharCode(parseInt(h, 16));
|
||||||
}).join('');
|
})
|
||||||
};
|
.join('');
|
||||||
|
};
|
||||||
|
|
||||||
Enc.urlBase64ToBase64 = function urlsafeBase64ToBase64(str) {
|
Enc.urlBase64ToBase64 = function urlsafeBase64ToBase64(str) {
|
||||||
var r = str % 4;
|
var r = str % 4;
|
||||||
if (2 === r) {
|
if (2 === r) {
|
||||||
str += '==';
|
str += '==';
|
||||||
|
@ -134,7 +147,5 @@ Enc.urlBase64ToBase64 = function urlsafeBase64ToBase64(str) {
|
||||||
str += '=';
|
str += '=';
|
||||||
}
|
}
|
||||||
return str.replace(/-/g, '+').replace(/_/g, '/');
|
return str.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
};
|
};
|
||||||
|
})('undefined' !== typeof exports ? module.exports : window);
|
||||||
|
|
||||||
}('undefined' !== typeof exports ? module.exports : window ));
|
|
||||||
|
|
360
lib/keypairs.js
360
lib/keypairs.js
|
@ -1,75 +1,94 @@
|
||||||
/*global Promise*/
|
/*global Promise*/
|
||||||
(function (exports) {
|
(function(exports) {
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var Keypairs = exports.Keypairs = {};
|
var Keypairs = (exports.Keypairs = {});
|
||||||
var Rasha = exports.Rasha;
|
var Rasha = exports.Rasha;
|
||||||
var Eckles = exports.Eckles;
|
var Eckles = exports.Eckles;
|
||||||
var Enc = exports.Enc || {};
|
var Enc = exports.Enc || {};
|
||||||
|
|
||||||
Keypairs._stance = "We take the stance that if you're knowledgeable enough to"
|
Keypairs._stance =
|
||||||
+ " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway.";
|
"We take the stance that if you're knowledgeable enough to" +
|
||||||
Keypairs._universal = "Bluecrypt only supports crypto with standard cross-browser and cross-platform support.";
|
" properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway.";
|
||||||
Keypairs.generate = function (opts) {
|
Keypairs._universal =
|
||||||
|
'Bluecrypt only supports crypto with standard cross-browser and cross-platform support.';
|
||||||
|
Keypairs.generate = function(opts) {
|
||||||
opts = opts || {};
|
opts = opts || {};
|
||||||
var p;
|
var p;
|
||||||
if (!opts.kty) { opts.kty = opts.type; }
|
if (!opts.kty) {
|
||||||
if (!opts.kty) { opts.kty = 'EC'; }
|
opts.kty = opts.type;
|
||||||
|
}
|
||||||
|
if (!opts.kty) {
|
||||||
|
opts.kty = 'EC';
|
||||||
|
}
|
||||||
if (/^EC/i.test(opts.kty)) {
|
if (/^EC/i.test(opts.kty)) {
|
||||||
p = Eckles.generate(opts);
|
p = Eckles.generate(opts);
|
||||||
} else if (/^RSA$/i.test(opts.kty)) {
|
} else if (/^RSA$/i.test(opts.kty)) {
|
||||||
p = Rasha.generate(opts);
|
p = Rasha.generate(opts);
|
||||||
} else {
|
} else {
|
||||||
return Promise.Reject(new Error("'" + opts.kty + "' is not a well-supported key type."
|
return Promise.Reject(
|
||||||
+ Keypairs._universal
|
new Error(
|
||||||
+ " Please choose 'EC', or 'RSA' if you have good reason to."));
|
"'" +
|
||||||
|
opts.kty +
|
||||||
|
"' is not a well-supported key type." +
|
||||||
|
Keypairs._universal +
|
||||||
|
" Please choose 'EC', or 'RSA' if you have good reason to."
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return p.then(function (pair) {
|
return p.then(function(pair) {
|
||||||
return Keypairs.thumbprint({ jwk: pair.public }).then(function (thumb) {
|
return Keypairs.thumbprint({ jwk: pair.public }).then(function(
|
||||||
|
thumb
|
||||||
|
) {
|
||||||
pair.private.kid = thumb; // maybe not the same id on the private key?
|
pair.private.kid = thumb; // maybe not the same id on the private key?
|
||||||
pair.public.kid = thumb;
|
pair.public.kid = thumb;
|
||||||
return pair;
|
return pair;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Keypairs.export = function (opts) {
|
Keypairs.export = function(opts) {
|
||||||
return Eckles.export(opts).catch(function (err) {
|
return Eckles.export(opts).catch(function(err) {
|
||||||
return Rasha.export(opts).catch(function () {
|
return Rasha.export(opts).catch(function() {
|
||||||
return Promise.reject(err);
|
return Promise.reject(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
/**
|
|
||||||
* Chopping off the private parts is now part of the public API.
|
* Chopping off the private parts is now part of the public API.
|
||||||
* I thought it sounded a little too crude at first, but it really is the best name in every possible way.
|
* I thought it sounded a little too crude at first, but it really is the best name in every possible way.
|
||||||
*/
|
*/
|
||||||
Keypairs.neuter = function (opts) {
|
Keypairs.neuter = function(opts) {
|
||||||
/** trying to find the best balance of an immutable copy with custom attributes */
|
/** trying to find the best balance of an immutable copy with custom attributes */
|
||||||
var jwk = {};
|
var jwk = {};
|
||||||
Object.keys(opts.jwk).forEach(function (k) {
|
Object.keys(opts.jwk).forEach(function(k) {
|
||||||
if ('undefined' === typeof opts.jwk[k]) { return; }
|
if ('undefined' === typeof opts.jwk[k]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
// ignore RSA and EC private parts
|
// ignore RSA and EC private parts
|
||||||
if (-1 !== ['d', 'p', 'q', 'dp', 'dq', 'qi'].indexOf(k)) { return; }
|
if (-1 !== ['d', 'p', 'q', 'dp', 'dq', 'qi'].indexOf(k)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k]));
|
jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k]));
|
||||||
});
|
});
|
||||||
return jwk;
|
return jwk;
|
||||||
};
|
};
|
||||||
|
|
||||||
Keypairs.thumbprint = function (opts) {
|
Keypairs.thumbprint = function(opts) {
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
if (/EC/i.test(opts.jwk.kty)) {
|
if (/EC/i.test(opts.jwk.kty)) {
|
||||||
return Eckles.thumbprint(opts);
|
return Eckles.thumbprint(opts);
|
||||||
} else {
|
} else {
|
||||||
return Rasha.thumbprint(opts);
|
return Rasha.thumbprint(opts);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Keypairs.publish = function (opts) {
|
Keypairs.publish = function(opts) {
|
||||||
if ('object' !== typeof opts.jwk || !opts.jwk.kty) { throw new Error("invalid jwk: " + JSON.stringify(opts.jwk)); }
|
if ('object' !== typeof opts.jwk || !opts.jwk.kty) {
|
||||||
|
throw new Error('invalid jwk: ' + JSON.stringify(opts.jwk));
|
||||||
|
}
|
||||||
|
|
||||||
/** returns a copy */
|
/** returns a copy */
|
||||||
var jwk = Keypairs.neuter(opts);
|
var jwk = Keypairs.neuter(opts);
|
||||||
|
@ -77,67 +96,94 @@ Keypairs.publish = function (opts) {
|
||||||
if (jwk.exp) {
|
if (jwk.exp) {
|
||||||
jwk.exp = setTime(jwk.exp);
|
jwk.exp = setTime(jwk.exp);
|
||||||
} else {
|
} else {
|
||||||
if (opts.exp) { jwk.exp = setTime(opts.exp); }
|
if (opts.exp) {
|
||||||
else if (opts.expiresIn) { jwk.exp = Math.round(Date.now()/1000) + opts.expiresIn; }
|
jwk.exp = setTime(opts.exp);
|
||||||
else if (opts.expiresAt) { jwk.exp = opts.expiresAt; }
|
} else if (opts.expiresIn) {
|
||||||
|
jwk.exp = Math.round(Date.now() / 1000) + opts.expiresIn;
|
||||||
|
} else if (opts.expiresAt) {
|
||||||
|
jwk.exp = opts.expiresAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!jwk.use && false !== jwk.use) {
|
||||||
|
jwk.use = 'sig';
|
||||||
}
|
}
|
||||||
if (!jwk.use && false !== jwk.use) { jwk.use = "sig"; }
|
|
||||||
|
|
||||||
if (jwk.kid) { return Promise.resolve(jwk); }
|
if (jwk.kid) {
|
||||||
return Keypairs.thumbprint({ jwk: jwk }).then(function (thumb) { jwk.kid = thumb; return jwk; });
|
return Promise.resolve(jwk);
|
||||||
};
|
}
|
||||||
|
return Keypairs.thumbprint({ jwk: jwk }).then(function(thumb) {
|
||||||
|
jwk.kid = thumb;
|
||||||
|
return jwk;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// JWT a.k.a. JWS with Claims using Compact Serialization
|
// JWT a.k.a. JWS with Claims using Compact Serialization
|
||||||
Keypairs.signJwt = function (opts) {
|
Keypairs.signJwt = function(opts) {
|
||||||
return Keypairs.thumbprint({ jwk: opts.jwk }).then(function (thumb) {
|
return Keypairs.thumbprint({ jwk: opts.jwk }).then(function(thumb) {
|
||||||
var header = opts.header || {};
|
var header = opts.header || {};
|
||||||
var claims = JSON.parse(JSON.stringify(opts.claims || {}));
|
var claims = JSON.parse(JSON.stringify(opts.claims || {}));
|
||||||
header.typ = 'JWT';
|
header.typ = 'JWT';
|
||||||
|
|
||||||
if (!header.kid) { header.kid = thumb; }
|
if (!header.kid) {
|
||||||
if (!header.alg && opts.alg) { header.alg = opts.alg; }
|
header.kid = thumb;
|
||||||
|
}
|
||||||
|
if (!header.alg && opts.alg) {
|
||||||
|
header.alg = opts.alg;
|
||||||
|
}
|
||||||
if (!claims.iat && (false === claims.iat || false === opts.iat)) {
|
if (!claims.iat && (false === claims.iat || false === opts.iat)) {
|
||||||
claims.iat = undefined;
|
claims.iat = undefined;
|
||||||
} else if (!claims.iat) {
|
} else if (!claims.iat) {
|
||||||
claims.iat = Math.round(Date.now()/1000);
|
claims.iat = Math.round(Date.now() / 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opts.exp) {
|
if (opts.exp) {
|
||||||
claims.exp = setTime(opts.exp);
|
claims.exp = setTime(opts.exp);
|
||||||
} else if (!claims.exp && (false === claims.exp || false === opts.exp)) {
|
} else if (
|
||||||
|
!claims.exp &&
|
||||||
|
(false === claims.exp || false === opts.exp)
|
||||||
|
) {
|
||||||
claims.exp = undefined;
|
claims.exp = undefined;
|
||||||
} else if (!claims.exp) {
|
} else if (!claims.exp) {
|
||||||
throw new Error("opts.claims.exp should be the expiration date as seconds, human form (i.e. '1h' or '15m') or false");
|
throw new Error(
|
||||||
|
"opts.claims.exp should be the expiration date as seconds, human form (i.e. '1h' or '15m') or false"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opts.iss) { claims.iss = opts.iss; }
|
if (opts.iss) {
|
||||||
|
claims.iss = opts.iss;
|
||||||
|
}
|
||||||
if (!claims.iss && (false === claims.iss || false === opts.iss)) {
|
if (!claims.iss && (false === claims.iss || false === opts.iss)) {
|
||||||
claims.iss = undefined;
|
claims.iss = undefined;
|
||||||
} else if (!claims.iss) {
|
} else if (!claims.iss) {
|
||||||
throw new Error("opts.claims.iss should be in the form of https://example.com/, a secure OIDC base url");
|
throw new Error(
|
||||||
|
'opts.claims.iss should be in the form of https://example.com/, a secure OIDC base url'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Keypairs.signJws({
|
return Keypairs.signJws({
|
||||||
jwk: opts.jwk
|
jwk: opts.jwk,
|
||||||
, pem: opts.pem
|
pem: opts.pem,
|
||||||
, protected: header
|
protected: header,
|
||||||
, header: undefined
|
header: undefined,
|
||||||
, payload: claims
|
payload: claims
|
||||||
}).then(function (jws) {
|
}).then(function(jws) {
|
||||||
return [ jws.protected, jws.payload, jws.signature ].join('.');
|
return [jws.protected, jws.payload, jws.signature].join('.');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Keypairs.signJws = function (opts) {
|
|
||||||
return Keypairs.thumbprint(opts).then(function (thumb) {
|
|
||||||
|
|
||||||
|
Keypairs.signJws = function(opts) {
|
||||||
|
return Keypairs.thumbprint(opts).then(function(thumb) {
|
||||||
function alg() {
|
function alg() {
|
||||||
if (!opts.jwk) {
|
if (!opts.jwk) {
|
||||||
throw new Error("opts.jwk must exist and must declare 'typ'");
|
throw new Error(
|
||||||
|
"opts.jwk must exist and must declare 'typ'"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (opts.jwk.alg) { return opts.jwk.alg; }
|
if (opts.jwk.alg) {
|
||||||
var typ = ('RSA' === opts.jwk.kty) ? "RS" : "ES";
|
return opts.jwk.alg;
|
||||||
|
}
|
||||||
|
var typ = 'RSA' === opts.jwk.kty ? 'RS' : 'ES';
|
||||||
return typ + Keypairs._getBits(opts);
|
return typ + Keypairs._getBits(opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -146,15 +192,22 @@ Keypairs.signJws = function (opts) {
|
||||||
var payload = opts.payload;
|
var payload = opts.payload;
|
||||||
|
|
||||||
// Compute JWS signature
|
// Compute JWS signature
|
||||||
var protectedHeader = "";
|
var protectedHeader = '';
|
||||||
// Because unprotected headers are allowed, regrettably...
|
// Because unprotected headers are allowed, regrettably...
|
||||||
// https://stackoverflow.com/a/46288694
|
// https://stackoverflow.com/a/46288694
|
||||||
if (false !== protect) {
|
if (false !== protect) {
|
||||||
if (!protect) { protect = {}; }
|
if (!protect) {
|
||||||
if (!protect.alg) { protect.alg = alg(); }
|
protect = {};
|
||||||
|
}
|
||||||
|
if (!protect.alg) {
|
||||||
|
protect.alg = alg();
|
||||||
|
}
|
||||||
// There's a particular request where ACME / Let's Encrypt explicitly doesn't use a kid
|
// There's a particular request where ACME / Let's Encrypt explicitly doesn't use a kid
|
||||||
if (false === protect.kid) { protect.kid = undefined; }
|
if (false === protect.kid) {
|
||||||
else if (!protect.kid) { protect.kid = thumb; }
|
protect.kid = undefined;
|
||||||
|
} else if (!protect.kid) {
|
||||||
|
protect.kid = thumb;
|
||||||
|
}
|
||||||
protectedHeader = JSON.stringify(protect);
|
protectedHeader = JSON.stringify(protect);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -163,9 +216,11 @@ Keypairs.signJws = function (opts) {
|
||||||
// throw new Error("opts.payload should be JSON, string, or ArrayBuffer (it may be empty, but that must be explicit)");
|
// throw new Error("opts.payload should be JSON, string, or ArrayBuffer (it may be empty, but that must be explicit)");
|
||||||
//}
|
//}
|
||||||
// Trying to detect if it's a plain object (not Buffer, ArrayBuffer, Array, Uint8Array, etc)
|
// Trying to detect if it's a plain object (not Buffer, ArrayBuffer, Array, Uint8Array, etc)
|
||||||
if (payload && ('string' !== typeof payload)
|
if (
|
||||||
&& ('undefined' === typeof payload.byteLength)
|
payload &&
|
||||||
&& ('undefined' === typeof payload.buffer)
|
'string' !== typeof payload &&
|
||||||
|
'undefined' === typeof payload.byteLength &&
|
||||||
|
'undefined' === typeof payload.buffer
|
||||||
) {
|
) {
|
||||||
payload = JSON.stringify(payload);
|
payload = JSON.stringify(payload);
|
||||||
}
|
}
|
||||||
|
@ -179,11 +234,11 @@ Keypairs.signJws = function (opts) {
|
||||||
var payload64 = Enc.bufToUrlBase64(payload);
|
var payload64 = Enc.bufToUrlBase64(payload);
|
||||||
var msg = protected64 + '.' + payload64;
|
var msg = protected64 + '.' + payload64;
|
||||||
|
|
||||||
return Keypairs._sign(opts, msg).then(function (buf) {
|
return Keypairs._sign(opts, msg).then(function(buf) {
|
||||||
var signedMsg = {
|
var signedMsg = {
|
||||||
protected: protected64
|
protected: protected64,
|
||||||
, payload: payload64
|
payload: payload64,
|
||||||
, signature: Enc.bufToUrlBase64(buf)
|
signature: Enc.bufToUrlBase64(buf)
|
||||||
};
|
};
|
||||||
|
|
||||||
return signedMsg;
|
return signedMsg;
|
||||||
|
@ -193,29 +248,35 @@ Keypairs.signJws = function (opts) {
|
||||||
if (opts.jwk) {
|
if (opts.jwk) {
|
||||||
return sign();
|
return sign();
|
||||||
} else {
|
} else {
|
||||||
return Keypairs.import({ pem: opts.pem }).then(function (pair) {
|
return Keypairs.import({ pem: opts.pem }).then(function(pair) {
|
||||||
opts.jwk = pair.private;
|
opts.jwk = pair.private;
|
||||||
return sign();
|
return sign();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Keypairs._sign = function (opts, payload) {
|
Keypairs._sign = function(opts, payload) {
|
||||||
return Keypairs._import(opts).then(function (privkey) {
|
return Keypairs._import(opts).then(function(privkey) {
|
||||||
if ('string' === typeof payload) {
|
if ('string' === typeof payload) {
|
||||||
payload = (new TextEncoder()).encode(payload);
|
payload = new TextEncoder().encode(payload);
|
||||||
}
|
}
|
||||||
return window.crypto.subtle.sign(
|
return window.crypto.subtle
|
||||||
{ name: Keypairs._getName(opts)
|
.sign(
|
||||||
, hash: { name: 'SHA-' + Keypairs._getBits(opts) }
|
{
|
||||||
}
|
name: Keypairs._getName(opts),
|
||||||
, privkey
|
hash: { name: 'SHA-' + Keypairs._getBits(opts) }
|
||||||
, payload
|
},
|
||||||
).then(function (signature) {
|
privkey,
|
||||||
|
payload
|
||||||
|
)
|
||||||
|
.then(function(signature) {
|
||||||
signature = new Uint8Array(signature); // ArrayBuffer -> u8
|
signature = new Uint8Array(signature); // ArrayBuffer -> u8
|
||||||
// This will come back into play for CSRs, but not for JOSE
|
// This will come back into play for CSRs, but not for JOSE
|
||||||
if ('EC' === opts.jwk.kty && /x509|asn1/i.test(opts.format)) {
|
if (
|
||||||
|
'EC' === opts.jwk.kty &&
|
||||||
|
/x509|asn1/i.test(opts.format)
|
||||||
|
) {
|
||||||
return Keypairs._ecdsaJoseSigToAsn1Sig(signature);
|
return Keypairs._ecdsaJoseSigToAsn1Sig(signature);
|
||||||
} else {
|
} else {
|
||||||
// jose/jws/jwt
|
// jose/jws/jwt
|
||||||
|
@ -223,11 +284,13 @@ Keypairs._sign = function (opts, payload) {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
Keypairs._getBits = function (opts) {
|
Keypairs._getBits = function(opts) {
|
||||||
if (opts.alg) { return opts.alg.replace(/[a-z\-]/ig, ''); }
|
if (opts.alg) {
|
||||||
|
return opts.alg.replace(/[a-z\-]/gi, '');
|
||||||
|
}
|
||||||
// base64 len to byte len
|
// base64 len to byte len
|
||||||
var len = Math.floor((opts.jwk.n||'').length * 0.75);
|
var len = Math.floor((opts.jwk.n || '').length * 0.75);
|
||||||
|
|
||||||
// TODO this may be a bug
|
// TODO this may be a bug
|
||||||
// need to confirm that the padding is no more or less than 1 byte
|
// need to confirm that the padding is no more or less than 1 byte
|
||||||
|
@ -238,79 +301,101 @@ Keypairs._getBits = function (opts) {
|
||||||
}
|
}
|
||||||
|
|
||||||
return '256';
|
return '256';
|
||||||
};
|
};
|
||||||
Keypairs._getName = function (opts) {
|
Keypairs._getName = function(opts) {
|
||||||
if (/EC/i.test(opts.jwk.kty)) {
|
if (/EC/i.test(opts.jwk.kty)) {
|
||||||
return 'ECDSA';
|
return 'ECDSA';
|
||||||
} else {
|
} else {
|
||||||
return 'RSASSA-PKCS1-v1_5';
|
return 'RSASSA-PKCS1-v1_5';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Keypairs._import = function (opts) {
|
Keypairs._import = function(opts) {
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
var ops;
|
var ops;
|
||||||
// all private keys just happen to have a 'd'
|
// all private keys just happen to have a 'd'
|
||||||
if (opts.jwk.d) {
|
if (opts.jwk.d) {
|
||||||
ops = [ 'sign' ];
|
ops = ['sign'];
|
||||||
} else {
|
} else {
|
||||||
ops = [ 'verify' ];
|
ops = ['verify'];
|
||||||
}
|
}
|
||||||
// gotta mark it as extractable, as if it matters
|
// gotta mark it as extractable, as if it matters
|
||||||
opts.jwk.ext = true;
|
opts.jwk.ext = true;
|
||||||
opts.jwk.key_ops = ops;
|
opts.jwk.key_ops = ops;
|
||||||
|
|
||||||
return window.crypto.subtle.importKey(
|
return window.crypto.subtle
|
||||||
"jwk"
|
.importKey(
|
||||||
, opts.jwk
|
'jwk',
|
||||||
, { name: Keypairs._getName(opts)
|
opts.jwk,
|
||||||
, namedCurve: opts.jwk.crv
|
{
|
||||||
, hash: { name: 'SHA-' + Keypairs._getBits(opts) } }
|
name: Keypairs._getName(opts),
|
||||||
, true
|
namedCurve: opts.jwk.crv,
|
||||||
, ops
|
hash: { name: 'SHA-' + Keypairs._getBits(opts) }
|
||||||
).then(function (privkey) {
|
},
|
||||||
|
true,
|
||||||
|
ops
|
||||||
|
)
|
||||||
|
.then(function(privkey) {
|
||||||
delete opts.jwk.ext;
|
delete opts.jwk.ext;
|
||||||
return privkey;
|
return privkey;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
// ECDSA JOSE / JWS / JWT signatures differ from "normal" ASN1/X509 ECDSA signatures
|
// ECDSA JOSE / JWS / JWT signatures differ from "normal" ASN1/X509 ECDSA signatures
|
||||||
// https://tools.ietf.org/html/rfc7518#section-3.4
|
// https://tools.ietf.org/html/rfc7518#section-3.4
|
||||||
Keypairs._ecdsaJoseSigToAsn1Sig = function (bufsig) {
|
Keypairs._ecdsaJoseSigToAsn1Sig = function(bufsig) {
|
||||||
// it's easier to do the manipulation in the browser with an array
|
// it's easier to do the manipulation in the browser with an array
|
||||||
bufsig = Array.from(bufsig);
|
bufsig = Array.from(bufsig);
|
||||||
var hlen = bufsig.length / 2; // should be even
|
var hlen = bufsig.length / 2; // should be even
|
||||||
var r = bufsig.slice(0, hlen);
|
var r = bufsig.slice(0, hlen);
|
||||||
var s = bufsig.slice(hlen);
|
var s = bufsig.slice(hlen);
|
||||||
// unpad positive ints less than 32 bytes wide
|
// unpad positive ints less than 32 bytes wide
|
||||||
while (!r[0]) { r = r.slice(1); }
|
while (!r[0]) {
|
||||||
while (!s[0]) { s = s.slice(1); }
|
r = r.slice(1);
|
||||||
|
}
|
||||||
|
while (!s[0]) {
|
||||||
|
s = s.slice(1);
|
||||||
|
}
|
||||||
// pad (or re-pad) ambiguously non-negative BigInts, up to 33 bytes wide
|
// pad (or re-pad) ambiguously non-negative BigInts, up to 33 bytes wide
|
||||||
if (0x80 & r[0]) { r.unshift(0); }
|
if (0x80 & r[0]) {
|
||||||
if (0x80 & s[0]) { s.unshift(0); }
|
r.unshift(0);
|
||||||
|
}
|
||||||
|
if (0x80 & s[0]) {
|
||||||
|
s.unshift(0);
|
||||||
|
}
|
||||||
|
|
||||||
var len = 2 + r.length + 2 + s.length;
|
var len = 2 + r.length + 2 + s.length;
|
||||||
var head = [0x30];
|
var head = [0x30];
|
||||||
// hard code 0x80 + 1 because it won't be longer than
|
// hard code 0x80 + 1 because it won't be longer than
|
||||||
// two SHA512 plus two pad bytes (130 bytes <= 256)
|
// two SHA512 plus two pad bytes (130 bytes <= 256)
|
||||||
if (len >= 0x80) { head.push(0x81); }
|
if (len >= 0x80) {
|
||||||
|
head.push(0x81);
|
||||||
|
}
|
||||||
head.push(len);
|
head.push(len);
|
||||||
|
|
||||||
return Uint8Array.from(head.concat([0x02, r.length], r, [0x02, s.length], s));
|
return Uint8Array.from(
|
||||||
};
|
head.concat([0x02, r.length], r, [0x02, s.length], s)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
function setTime(time) {
|
function setTime(time) {
|
||||||
if ('number' === typeof time) { return time; }
|
if ('number' === typeof time) {
|
||||||
|
return time;
|
||||||
|
}
|
||||||
|
|
||||||
var t = time.match(/^(\-?\d+)([dhms])$/i);
|
var t = time.match(/^(\-?\d+)([dhms])$/i);
|
||||||
if (!t || !t[0]) {
|
if (!t || !t[0]) {
|
||||||
throw new Error("'" + time + "' should be datetime in seconds or human-readable format (i.e. 3d, 1h, 15m, 30s");
|
throw new Error(
|
||||||
|
"'" +
|
||||||
|
time +
|
||||||
|
"' should be datetime in seconds or human-readable format (i.e. 3d, 1h, 15m, 30s"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
var now = Math.round(Date.now()/1000);
|
var now = Math.round(Date.now() / 1000);
|
||||||
var num = parseInt(t[1], 10);
|
var num = parseInt(t[1], 10);
|
||||||
var unit = t[2];
|
var unit = t[2];
|
||||||
var mult = 1;
|
var mult = 1;
|
||||||
switch(unit) {
|
switch (unit) {
|
||||||
// fancy fallthrough, what fun!
|
// fancy fallthrough, what fun!
|
||||||
case 'd':
|
case 'd':
|
||||||
mult *= 24;
|
mult *= 24;
|
||||||
|
@ -325,24 +410,23 @@ function setTime(time) {
|
||||||
mult *= 1;
|
mult *= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
return now + (mult * num);
|
return now + mult * num;
|
||||||
}
|
}
|
||||||
|
|
||||||
Enc.hexToBuf = function (hex) {
|
Enc.hexToBuf = function(hex) {
|
||||||
var arr = [];
|
var arr = [];
|
||||||
hex.match(/.{2}/g).forEach(function (h) {
|
hex.match(/.{2}/g).forEach(function(h) {
|
||||||
arr.push(parseInt(h, 16));
|
arr.push(parseInt(h, 16));
|
||||||
});
|
});
|
||||||
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
||||||
};
|
};
|
||||||
Enc.strToUrlBase64 = function (str) {
|
Enc.strToUrlBase64 = function(str) {
|
||||||
return Enc.bufToUrlBase64(Enc.binToBuf(str));
|
return Enc.bufToUrlBase64(Enc.binToBuf(str));
|
||||||
};
|
};
|
||||||
Enc.binToBuf = function (bin) {
|
Enc.binToBuf = function(bin) {
|
||||||
var arr = bin.split('').map(function (ch) {
|
var arr = bin.split('').map(function(ch) {
|
||||||
return ch.charCodeAt(0);
|
return ch.charCodeAt(0);
|
||||||
});
|
});
|
||||||
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr;
|
||||||
};
|
};
|
||||||
|
})('undefined' !== typeof module ? module.exports : window);
|
||||||
}('undefined' !== typeof module ? module.exports : window));
|
|
||||||
|
|
208
lib/rsa.js
208
lib/rsa.js
|
@ -1,22 +1,30 @@
|
||||||
/*global Promise*/
|
/*global Promise*/
|
||||||
(function (exports) {
|
(function(exports) {
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var RSA = exports.Rasha = {};
|
var RSA = (exports.Rasha = {});
|
||||||
var x509 = exports.x509;
|
var x509 = exports.x509;
|
||||||
if ('undefined' !== typeof module) { module.exports = RSA; }
|
if ('undefined' !== typeof module) {
|
||||||
var PEM = exports.PEM;
|
module.exports = RSA;
|
||||||
var SSH = exports.SSH;
|
}
|
||||||
var Enc = {};
|
var PEM = exports.PEM;
|
||||||
var textEncoder = new TextEncoder();
|
var SSH = exports.SSH;
|
||||||
|
var Enc = {};
|
||||||
|
var textEncoder = new TextEncoder();
|
||||||
|
|
||||||
RSA._stance = "We take the stance that if you're knowledgeable enough to"
|
RSA._stance =
|
||||||
+ " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway.";
|
"We take the stance that if you're knowledgeable enough to" +
|
||||||
RSA._universal = "Bluecrypt only supports crypto with standard cross-browser and cross-platform support.";
|
" properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway.";
|
||||||
RSA.generate = function (opts) {
|
RSA._universal =
|
||||||
|
'Bluecrypt only supports crypto with standard cross-browser and cross-platform support.';
|
||||||
|
RSA.generate = function(opts) {
|
||||||
var wcOpts = {};
|
var wcOpts = {};
|
||||||
if (!opts) { opts = {}; }
|
if (!opts) {
|
||||||
if (!opts.kty) { opts.kty = 'RSA'; }
|
opts = {};
|
||||||
|
}
|
||||||
|
if (!opts.kty) {
|
||||||
|
opts.kty = 'RSA';
|
||||||
|
}
|
||||||
|
|
||||||
// Support PSS? I don't think it's used for Let's Encrypt
|
// Support PSS? I don't think it's used for Let's Encrypt
|
||||||
wcOpts.name = 'RSASSA-PKCS1-v1_5';
|
wcOpts.name = 'RSASSA-PKCS1-v1_5';
|
||||||
|
@ -26,55 +34,66 @@ RSA.generate = function (opts) {
|
||||||
wcOpts.modulusLength = opts.modulusLength;
|
wcOpts.modulusLength = opts.modulusLength;
|
||||||
if (wcOpts.modulusLength >= 2048 && wcOpts.modulusLength < 3072) {
|
if (wcOpts.modulusLength >= 2048 && wcOpts.modulusLength < 3072) {
|
||||||
// erring on the small side... for no good reason
|
// erring on the small side... for no good reason
|
||||||
wcOpts.hash = { name: "SHA-256" };
|
wcOpts.hash = { name: 'SHA-256' };
|
||||||
} else if (wcOpts.modulusLength >= 3072 && wcOpts.modulusLength < 4096) {
|
} else if (
|
||||||
wcOpts.hash = { name: "SHA-384" };
|
wcOpts.modulusLength >= 3072 &&
|
||||||
|
wcOpts.modulusLength < 4096
|
||||||
|
) {
|
||||||
|
wcOpts.hash = { name: 'SHA-384' };
|
||||||
} else if (wcOpts.modulusLength < 4097) {
|
} else if (wcOpts.modulusLength < 4097) {
|
||||||
wcOpts.hash = { name: "SHA-512" };
|
wcOpts.hash = { name: 'SHA-512' };
|
||||||
} else {
|
} else {
|
||||||
// Public key thumbprints should be paired with a hash of similar length,
|
// Public key thumbprints should be paired with a hash of similar length,
|
||||||
// so anything above SHA-512's keyspace would be left under-represented anyway.
|
// so anything above SHA-512's keyspace would be left under-represented anyway.
|
||||||
return Promise.Reject(new Error("'" + wcOpts.modulusLength + "' is not within the safe and universally"
|
return Promise.Reject(
|
||||||
+ " acceptable range of 2048-4096. Typically you should pick 2048, 3072, or 4096, though other values"
|
new Error(
|
||||||
+ " divisible by 8 are allowed. " + RSA._stance));
|
"'" +
|
||||||
|
wcOpts.modulusLength +
|
||||||
|
"' is not within the safe and universally" +
|
||||||
|
' acceptable range of 2048-4096. Typically you should pick 2048, 3072, or 4096, though other values' +
|
||||||
|
' divisible by 8 are allowed. ' +
|
||||||
|
RSA._stance
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
// TODO maybe allow this to be set to any of the standard values?
|
// TODO maybe allow this to be set to any of the standard values?
|
||||||
wcOpts.publicExponent = new Uint8Array([0x01, 0x00, 0x01]);
|
wcOpts.publicExponent = new Uint8Array([0x01, 0x00, 0x01]);
|
||||||
|
|
||||||
var extractable = true;
|
var extractable = true;
|
||||||
return window.crypto.subtle.generateKey(
|
return window.crypto.subtle
|
||||||
wcOpts
|
.generateKey(wcOpts, extractable, ['sign', 'verify'])
|
||||||
, extractable
|
.then(function(result) {
|
||||||
, [ 'sign', 'verify' ]
|
return window.crypto.subtle
|
||||||
).then(function (result) {
|
.exportKey('jwk', result.privateKey)
|
||||||
return window.crypto.subtle.exportKey(
|
.then(function(privJwk) {
|
||||||
"jwk"
|
|
||||||
, result.privateKey
|
|
||||||
).then(function (privJwk) {
|
|
||||||
return {
|
return {
|
||||||
private: privJwk
|
private: privJwk,
|
||||||
, public: RSA.neuter({ jwk: privJwk })
|
public: RSA.neuter({ jwk: privJwk })
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Chopping off the private parts is now part of the public API.
|
// Chopping off the private parts is now part of the public API.
|
||||||
// I thought it sounded a little too crude at first, but it really is the best name in every possible way.
|
// I thought it sounded a little too crude at first, but it really is the best name in every possible way.
|
||||||
RSA.neuter = function (opts) {
|
RSA.neuter = function(opts) {
|
||||||
// trying to find the best balance of an immutable copy with custom attributes
|
// trying to find the best balance of an immutable copy with custom attributes
|
||||||
var jwk = {};
|
var jwk = {};
|
||||||
Object.keys(opts.jwk).forEach(function (k) {
|
Object.keys(opts.jwk).forEach(function(k) {
|
||||||
if ('undefined' === typeof opts.jwk[k]) { return; }
|
if ('undefined' === typeof opts.jwk[k]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
// ignore RSA private parts
|
// ignore RSA private parts
|
||||||
if (-1 !== ['d', 'p', 'q', 'dp', 'dq', 'qi'].indexOf(k)) { return; }
|
if (-1 !== ['d', 'p', 'q', 'dp', 'dq', 'qi'].indexOf(k)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k]));
|
jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k]));
|
||||||
});
|
});
|
||||||
return jwk;
|
return jwk;
|
||||||
};
|
};
|
||||||
|
|
||||||
// https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk
|
// https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk
|
||||||
RSA.__thumbprint = function (jwk) {
|
RSA.__thumbprint = function(jwk) {
|
||||||
// Use the same entropy for SHA as for key
|
// Use the same entropy for SHA as for key
|
||||||
var len = Math.floor(jwk.n.length * 0.75);
|
var len = Math.floor(jwk.n.length * 0.75);
|
||||||
var alg = 'SHA-256';
|
var alg = 'SHA-256';
|
||||||
|
@ -85,39 +104,46 @@ RSA.__thumbprint = function (jwk) {
|
||||||
} else if (len >= 383) {
|
} else if (len >= 383) {
|
||||||
alg = 'SHA-384';
|
alg = 'SHA-384';
|
||||||
}
|
}
|
||||||
return window.crypto.subtle.digest(
|
return window.crypto.subtle
|
||||||
{ name: alg }
|
.digest(
|
||||||
, textEncoder.encode('{"e":"' + jwk.e + '","kty":"RSA","n":"' + jwk.n + '"}')
|
{ name: alg },
|
||||||
).then(function (hash) {
|
textEncoder.encode(
|
||||||
|
'{"e":"' + jwk.e + '","kty":"RSA","n":"' + jwk.n + '"}'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.then(function(hash) {
|
||||||
return Enc.bufToUrlBase64(new Uint8Array(hash));
|
return Enc.bufToUrlBase64(new Uint8Array(hash));
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
RSA.thumbprint = function (opts) {
|
RSA.thumbprint = function(opts) {
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
var jwk;
|
var jwk;
|
||||||
if ('EC' === opts.kty) {
|
if ('EC' === opts.kty) {
|
||||||
jwk = opts;
|
jwk = opts;
|
||||||
} else if (opts.jwk) {
|
} else if (opts.jwk) {
|
||||||
jwk = opts.jwk;
|
jwk = opts.jwk;
|
||||||
} else {
|
} else {
|
||||||
return RSA.import(opts).then(function (jwk) {
|
return RSA.import(opts).then(function(jwk) {
|
||||||
return RSA.__thumbprint(jwk);
|
return RSA.__thumbprint(jwk);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return RSA.__thumbprint(jwk);
|
return RSA.__thumbprint(jwk);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
RSA.export = function (opts) {
|
RSA.export = function(opts) {
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
if (!opts || !opts.jwk || 'object' !== typeof opts.jwk) {
|
if (!opts || !opts.jwk || 'object' !== typeof opts.jwk) {
|
||||||
throw new Error("must pass { jwk: jwk }");
|
throw new Error('must pass { jwk: jwk }');
|
||||||
}
|
}
|
||||||
var jwk = JSON.parse(JSON.stringify(opts.jwk));
|
var jwk = JSON.parse(JSON.stringify(opts.jwk));
|
||||||
var format = opts.format;
|
var format = opts.format;
|
||||||
var pub = opts.public;
|
var pub = opts.public;
|
||||||
if (pub || -1 !== [ 'spki', 'pkix', 'ssh', 'rfc4716' ].indexOf(format)) {
|
if (
|
||||||
|
pub ||
|
||||||
|
-1 !== ['spki', 'pkix', 'ssh', 'rfc4716'].indexOf(format)
|
||||||
|
) {
|
||||||
jwk = RSA.neuter({ jwk: jwk });
|
jwk = RSA.neuter({ jwk: jwk });
|
||||||
}
|
}
|
||||||
if ('RSA' !== jwk.kty) {
|
if ('RSA' !== jwk.kty) {
|
||||||
|
@ -128,60 +154,82 @@ RSA.export = function (opts) {
|
||||||
pub = true;
|
pub = true;
|
||||||
if (!format || 'pkcs1' === format) {
|
if (!format || 'pkcs1' === format) {
|
||||||
format = 'pkcs1';
|
format = 'pkcs1';
|
||||||
} else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
|
} else if (-1 !== ['spki', 'pkix'].indexOf(format)) {
|
||||||
format = 'spki';
|
format = 'spki';
|
||||||
} else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
|
} else if (-1 !== ['ssh', 'rfc4716'].indexOf(format)) {
|
||||||
format = 'ssh';
|
format = 'ssh';
|
||||||
} else {
|
} else {
|
||||||
throw new Error("options.format must be 'spki', 'pkcs1', or 'ssh' for public RSA keys, not ("
|
throw new Error(
|
||||||
+ typeof format + ") " + format);
|
"options.format must be 'spki', 'pkcs1', or 'ssh' for public RSA keys, not (" +
|
||||||
|
typeof format +
|
||||||
|
') ' +
|
||||||
|
format
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// TODO test for all necessary keys (d, p, q ...)
|
// TODO test for all necessary keys (d, p, q ...)
|
||||||
if (!format || 'pkcs1' === format) {
|
if (!format || 'pkcs1' === format) {
|
||||||
format = 'pkcs1';
|
format = 'pkcs1';
|
||||||
} else if ('pkcs8' !== format) {
|
} else if ('pkcs8' !== format) {
|
||||||
throw new Error("options.format must be 'pkcs1' or 'pkcs8' for private RSA keys");
|
throw new Error(
|
||||||
|
"options.format must be 'pkcs1' or 'pkcs8' for private RSA keys"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('pkcs1' === format) {
|
if ('pkcs1' === format) {
|
||||||
if (jwk.d) {
|
if (jwk.d) {
|
||||||
return PEM.packBlock({ type: "RSA PRIVATE KEY", bytes: x509.packPkcs1(jwk) });
|
return PEM.packBlock({
|
||||||
|
type: 'RSA PRIVATE KEY',
|
||||||
|
bytes: x509.packPkcs1(jwk)
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
return PEM.packBlock({ type: "RSA PUBLIC KEY", bytes: x509.packPkcs1(jwk) });
|
return PEM.packBlock({
|
||||||
|
type: 'RSA PUBLIC KEY',
|
||||||
|
bytes: x509.packPkcs1(jwk)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} else if ('pkcs8' === format) {
|
} else if ('pkcs8' === format) {
|
||||||
return PEM.packBlock({ type: "PRIVATE KEY", bytes: x509.packPkcs8(jwk) });
|
return PEM.packBlock({
|
||||||
} else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
|
type: 'PRIVATE KEY',
|
||||||
return PEM.packBlock({ type: "PUBLIC KEY", bytes: x509.packSpki(jwk) });
|
bytes: x509.packPkcs8(jwk)
|
||||||
} else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
|
});
|
||||||
|
} else if (-1 !== ['spki', 'pkix'].indexOf(format)) {
|
||||||
|
return PEM.packBlock({
|
||||||
|
type: 'PUBLIC KEY',
|
||||||
|
bytes: x509.packSpki(jwk)
|
||||||
|
});
|
||||||
|
} else if (-1 !== ['ssh', 'rfc4716'].indexOf(format)) {
|
||||||
return SSH.pack({ jwk: jwk, comment: opts.comment });
|
return SSH.pack({ jwk: jwk, comment: opts.comment });
|
||||||
} else {
|
} else {
|
||||||
throw new Error("Sanity Error: reached unreachable code block with format: " + format);
|
throw new Error(
|
||||||
|
'Sanity Error: reached unreachable code block with format: ' +
|
||||||
|
format
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
RSA.pack = function (opts) {
|
RSA.pack = function(opts) {
|
||||||
// wrapped in a promise for API compatibility
|
// wrapped in a promise for API compatibility
|
||||||
// with the forthcoming browser version
|
// with the forthcoming browser version
|
||||||
// (and potential future native node capability)
|
// (and potential future native node capability)
|
||||||
return Promise.resolve().then(function () {
|
return Promise.resolve().then(function() {
|
||||||
return RSA.export(opts);
|
return RSA.export(opts);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Enc.bufToUrlBase64 = function (u8) {
|
Enc.bufToUrlBase64 = function(u8) {
|
||||||
return Enc.bufToBase64(u8)
|
return Enc.bufToBase64(u8)
|
||||||
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
|
.replace(/\+/g, '-')
|
||||||
};
|
.replace(/\//g, '_')
|
||||||
|
.replace(/=/g, '');
|
||||||
|
};
|
||||||
|
|
||||||
Enc.bufToBase64 = function (u8) {
|
Enc.bufToBase64 = function(u8) {
|
||||||
var bin = '';
|
var bin = '';
|
||||||
u8.forEach(function (i) {
|
u8.forEach(function(i) {
|
||||||
bin += String.fromCharCode(i);
|
bin += String.fromCharCode(i);
|
||||||
});
|
});
|
||||||
return btoa(bin);
|
return btoa(bin);
|
||||||
};
|
};
|
||||||
|
})('undefined' !== typeof module ? module.exports : window);
|
||||||
}('undefined' !== typeof module ? module.exports : window));
|
|
||||||
|
|
270
lib/x509.js
270
lib/x509.js
|
@ -1,7 +1,7 @@
|
||||||
(function (exports) {
|
(function(exports) {
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var x509 = exports.x509 = {};
|
var x509 = (exports.x509 = {});
|
||||||
var ASN1 = exports.ASN1;
|
var ASN1 = exports.ASN1;
|
||||||
var Enc = exports.Enc;
|
var Enc = exports.Enc;
|
||||||
|
|
||||||
|
@ -13,20 +13,22 @@
|
||||||
var OBJ_ID_EC_384 = '06 05 2B81040022'.replace(/\s+/g, '').toLowerCase();
|
var OBJ_ID_EC_384 = '06 05 2B81040022'.replace(/\s+/g, '').toLowerCase();
|
||||||
// 1.2.840.10045.2.1
|
// 1.2.840.10045.2.1
|
||||||
// ecPublicKey (ANSI X9.62 public key type)
|
// ecPublicKey (ANSI X9.62 public key type)
|
||||||
var OBJ_ID_EC_PUB = '06 07 2A8648CE3D0201'.replace(/\s+/g, '').toLowerCase();
|
var OBJ_ID_EC_PUB = '06 07 2A8648CE3D0201'
|
||||||
|
.replace(/\s+/g, '')
|
||||||
|
.toLowerCase();
|
||||||
|
|
||||||
x509.parseSec1 = function parseEcOnlyPrivkey(u8, jwk) {
|
x509.parseSec1 = function parseEcOnlyPrivkey(u8, jwk) {
|
||||||
var index = 7;
|
var index = 7;
|
||||||
var len = 32;
|
var len = 32;
|
||||||
var olen = OBJ_ID_EC.length / 2;
|
var olen = OBJ_ID_EC.length / 2;
|
||||||
|
|
||||||
if ("P-384" === jwk.crv) {
|
if ('P-384' === jwk.crv) {
|
||||||
olen = OBJ_ID_EC_384.length / 2;
|
olen = OBJ_ID_EC_384.length / 2;
|
||||||
index = 8;
|
index = 8;
|
||||||
len = 48;
|
len = 48;
|
||||||
}
|
}
|
||||||
if (len !== u8[index - 1]) {
|
if (len !== u8[index - 1]) {
|
||||||
throw new Error("Unexpected bitlength " + len);
|
throw new Error('Unexpected bitlength ' + len);
|
||||||
}
|
}
|
||||||
|
|
||||||
// private part is d
|
// private part is d
|
||||||
|
@ -39,23 +41,23 @@
|
||||||
if (0x04 === c) {
|
if (0x04 === c) {
|
||||||
y = u8.slice(ci + 1 + len, ci + 1 + len + len);
|
y = u8.slice(ci + 1 + len, ci + 1 + len + len);
|
||||||
} else if (0x02 !== c) {
|
} else if (0x02 !== c) {
|
||||||
throw new Error("not a supported EC private key");
|
throw new Error('not a supported EC private key');
|
||||||
}
|
}
|
||||||
x = u8.slice(ci + 1, ci + 1 + len);
|
x = u8.slice(ci + 1, ci + 1 + len);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
kty: jwk.kty
|
kty: jwk.kty,
|
||||||
, crv: jwk.crv
|
crv: jwk.crv,
|
||||||
, d: Enc.bufToUrlBase64(d)
|
d: Enc.bufToUrlBase64(d),
|
||||||
//, dh: Enc.bufToHex(d)
|
//, dh: Enc.bufToHex(d)
|
||||||
, x: Enc.bufToUrlBase64(x)
|
x: Enc.bufToUrlBase64(x),
|
||||||
//, xh: Enc.bufToHex(x)
|
//, xh: Enc.bufToHex(x)
|
||||||
, y: Enc.bufToUrlBase64(y)
|
y: Enc.bufToUrlBase64(y)
|
||||||
//, yh: Enc.bufToHex(y)
|
//, yh: Enc.bufToHex(y)
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
x509.packPkcs1 = function (jwk) {
|
x509.packPkcs1 = function(jwk) {
|
||||||
var n = ASN1.UInt(Enc.base64ToHex(jwk.n));
|
var n = ASN1.UInt(Enc.base64ToHex(jwk.n));
|
||||||
var e = ASN1.UInt(Enc.base64ToHex(jwk.e));
|
var e = ASN1.UInt(Enc.base64ToHex(jwk.e));
|
||||||
|
|
||||||
|
@ -63,31 +65,34 @@
|
||||||
return Enc.hexToBuf(ASN1('30', n, e));
|
return Enc.hexToBuf(ASN1('30', n, e));
|
||||||
}
|
}
|
||||||
|
|
||||||
return Enc.hexToBuf(ASN1('30'
|
return Enc.hexToBuf(
|
||||||
, ASN1.UInt('00')
|
ASN1(
|
||||||
, n
|
'30',
|
||||||
, e
|
ASN1.UInt('00'),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.d))
|
n,
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.p))
|
e,
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.q))
|
ASN1.UInt(Enc.base64ToHex(jwk.d)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.dp))
|
ASN1.UInt(Enc.base64ToHex(jwk.p)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.dq))
|
ASN1.UInt(Enc.base64ToHex(jwk.q)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.qi))
|
ASN1.UInt(Enc.base64ToHex(jwk.dp)),
|
||||||
));
|
ASN1.UInt(Enc.base64ToHex(jwk.dq)),
|
||||||
|
ASN1.UInt(Enc.base64ToHex(jwk.qi))
|
||||||
|
)
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
x509.parsePkcs8 = function parseEcPkcs8(u8, jwk) {
|
x509.parsePkcs8 = function parseEcPkcs8(u8, jwk) {
|
||||||
var index = 24 + (OBJ_ID_EC.length / 2);
|
var index = 24 + OBJ_ID_EC.length / 2;
|
||||||
var len = 32;
|
var len = 32;
|
||||||
if ("P-384" === jwk.crv) {
|
if ('P-384' === jwk.crv) {
|
||||||
index = 24 + (OBJ_ID_EC_384.length / 2) + 2;
|
index = 24 + OBJ_ID_EC_384.length / 2 + 2;
|
||||||
len = 48;
|
len = 48;
|
||||||
}
|
}
|
||||||
|
|
||||||
//console.log(index, u8.slice(index));
|
//console.log(index, u8.slice(index));
|
||||||
if (0x04 !== u8[index]) {
|
if (0x04 !== u8[index]) {
|
||||||
//console.log(jwk);
|
//console.log(jwk);
|
||||||
throw new Error("privkey not found");
|
throw new Error('privkey not found');
|
||||||
}
|
}
|
||||||
var d = u8.slice(index + 2, index + 2 + len);
|
var d = u8.slice(index + 2, index + 2 + len);
|
||||||
var ci = index + 2 + len + 5;
|
var ci = index + 2 + len + 5;
|
||||||
|
@ -98,17 +103,17 @@
|
||||||
if (0x04 === u8[ci]) {
|
if (0x04 === u8[ci]) {
|
||||||
y = u8.slice(yi, yi + len);
|
y = u8.slice(yi, yi + len);
|
||||||
} else if (0x02 !== u8[ci]) {
|
} else if (0x02 !== u8[ci]) {
|
||||||
throw new Error("invalid compression bit (expected 0x04 or 0x02)");
|
throw new Error('invalid compression bit (expected 0x04 or 0x02)');
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
kty: jwk.kty
|
kty: jwk.kty,
|
||||||
, crv: jwk.crv
|
crv: jwk.crv,
|
||||||
, d: Enc.bufToUrlBase64(d)
|
d: Enc.bufToUrlBase64(d),
|
||||||
//, dh: Enc.bufToHex(d)
|
//, dh: Enc.bufToHex(d)
|
||||||
, x: Enc.bufToUrlBase64(x)
|
x: Enc.bufToUrlBase64(x),
|
||||||
//, xh: Enc.bufToHex(x)
|
//, xh: Enc.bufToHex(x)
|
||||||
, y: Enc.bufToUrlBase64(y)
|
y: Enc.bufToUrlBase64(y)
|
||||||
//, yh: Enc.bufToHex(y)
|
//, yh: Enc.bufToHex(y)
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -117,7 +122,7 @@
|
||||||
var ci = 16 + OBJ_ID_EC.length / 2;
|
var ci = 16 + OBJ_ID_EC.length / 2;
|
||||||
var len = 32;
|
var len = 32;
|
||||||
|
|
||||||
if ("P-384" === jwk.crv) {
|
if ('P-384' === jwk.crv) {
|
||||||
ci = 16 + OBJ_ID_EC_384.length / 2;
|
ci = 16 + OBJ_ID_EC_384.length / 2;
|
||||||
len = 48;
|
len = 48;
|
||||||
}
|
}
|
||||||
|
@ -130,150 +135,167 @@
|
||||||
if (0x04 === c) {
|
if (0x04 === c) {
|
||||||
y = u8.slice(yi, yi + len);
|
y = u8.slice(yi, yi + len);
|
||||||
} else if (0x02 !== c) {
|
} else if (0x02 !== c) {
|
||||||
throw new Error("not a supported EC private key");
|
throw new Error('not a supported EC private key');
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
kty: jwk.kty
|
kty: jwk.kty,
|
||||||
, crv: jwk.crv
|
crv: jwk.crv,
|
||||||
, x: Enc.bufToUrlBase64(x)
|
x: Enc.bufToUrlBase64(x),
|
||||||
//, xh: Enc.bufToHex(x)
|
//, xh: Enc.bufToHex(x)
|
||||||
, y: Enc.bufToUrlBase64(y)
|
y: Enc.bufToUrlBase64(y)
|
||||||
//, yh: Enc.bufToHex(y)
|
//, yh: Enc.bufToHex(y)
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
x509.parsePkix = x509.parseSpki;
|
x509.parsePkix = x509.parseSpki;
|
||||||
|
|
||||||
x509.packSec1 = function (jwk) {
|
x509.packSec1 = function(jwk) {
|
||||||
var d = Enc.base64ToHex(jwk.d);
|
var d = Enc.base64ToHex(jwk.d);
|
||||||
var x = Enc.base64ToHex(jwk.x);
|
var x = Enc.base64ToHex(jwk.x);
|
||||||
var y = Enc.base64ToHex(jwk.y);
|
var y = Enc.base64ToHex(jwk.y);
|
||||||
var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
|
var objId = 'P-256' === jwk.crv ? OBJ_ID_EC : OBJ_ID_EC_384;
|
||||||
return Enc.hexToBuf(
|
return Enc.hexToBuf(
|
||||||
ASN1('30'
|
ASN1(
|
||||||
, ASN1.UInt('01')
|
'30',
|
||||||
, ASN1('04', d)
|
ASN1.UInt('01'),
|
||||||
, ASN1('A0', objId)
|
ASN1('04', d),
|
||||||
, ASN1('A1', ASN1.BitStr('04' + x + y)))
|
ASN1('A0', objId),
|
||||||
|
ASN1('A1', ASN1.BitStr('04' + x + y))
|
||||||
|
)
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* take a private jwk and creates a der from it
|
* take a private jwk and creates a der from it
|
||||||
* @param {*} jwk
|
* @param {*} jwk
|
||||||
*/
|
*/
|
||||||
x509.packPkcs8 = function (jwk) {
|
x509.packPkcs8 = function(jwk) {
|
||||||
if ('RSA' === jwk.kty) {
|
if ('RSA' === jwk.kty) {
|
||||||
if (!jwk.d) {
|
if (!jwk.d) {
|
||||||
// Public RSA
|
// Public RSA
|
||||||
return Enc.hexToBuf(ASN1('30'
|
return Enc.hexToBuf(
|
||||||
, ASN1('30'
|
ASN1(
|
||||||
, ASN1('06', '2a864886f70d010101')
|
'30',
|
||||||
, ASN1('05')
|
ASN1(
|
||||||
|
'30',
|
||||||
|
ASN1('06', '2a864886f70d010101'),
|
||||||
|
ASN1('05')
|
||||||
|
),
|
||||||
|
ASN1.BitStr(
|
||||||
|
ASN1(
|
||||||
|
'30',
|
||||||
|
ASN1.UInt(Enc.base64ToHex(jwk.n)),
|
||||||
|
ASN1.UInt(Enc.base64ToHex(jwk.e))
|
||||||
)
|
)
|
||||||
, ASN1.BitStr(ASN1('30'
|
)
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.n))
|
)
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.e))
|
);
|
||||||
))
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Private RSA
|
// Private RSA
|
||||||
return Enc.hexToBuf(ASN1('30'
|
return Enc.hexToBuf(
|
||||||
, ASN1.UInt('00')
|
ASN1(
|
||||||
, ASN1('30'
|
'30',
|
||||||
, ASN1('06', '2a864886f70d010101')
|
ASN1.UInt('00'),
|
||||||
, ASN1('05')
|
ASN1('30', ASN1('06', '2a864886f70d010101'), ASN1('05')),
|
||||||
)
|
ASN1(
|
||||||
, ASN1('04'
|
'04',
|
||||||
, ASN1('30'
|
ASN1(
|
||||||
, ASN1.UInt('00')
|
'30',
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.n))
|
ASN1.UInt('00'),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.e))
|
ASN1.UInt(Enc.base64ToHex(jwk.n)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.d))
|
ASN1.UInt(Enc.base64ToHex(jwk.e)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.p))
|
ASN1.UInt(Enc.base64ToHex(jwk.d)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.q))
|
ASN1.UInt(Enc.base64ToHex(jwk.p)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.dp))
|
ASN1.UInt(Enc.base64ToHex(jwk.q)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.dq))
|
ASN1.UInt(Enc.base64ToHex(jwk.dp)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.qi))
|
ASN1.UInt(Enc.base64ToHex(jwk.dq)),
|
||||||
|
ASN1.UInt(Enc.base64ToHex(jwk.qi))
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
));
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
var d = Enc.base64ToHex(jwk.d);
|
var d = Enc.base64ToHex(jwk.d);
|
||||||
var x = Enc.base64ToHex(jwk.x);
|
var x = Enc.base64ToHex(jwk.x);
|
||||||
var y = Enc.base64ToHex(jwk.y);
|
var y = Enc.base64ToHex(jwk.y);
|
||||||
var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
|
var objId = 'P-256' === jwk.crv ? OBJ_ID_EC : OBJ_ID_EC_384;
|
||||||
return Enc.hexToBuf(
|
return Enc.hexToBuf(
|
||||||
ASN1('30'
|
ASN1(
|
||||||
, ASN1.UInt('00')
|
'30',
|
||||||
, ASN1('30'
|
ASN1.UInt('00'),
|
||||||
, OBJ_ID_EC_PUB
|
ASN1('30', OBJ_ID_EC_PUB, objId),
|
||||||
, objId
|
ASN1(
|
||||||
|
'04',
|
||||||
|
ASN1(
|
||||||
|
'30',
|
||||||
|
ASN1.UInt('01'),
|
||||||
|
ASN1('04', d),
|
||||||
|
ASN1('A1', ASN1.BitStr('04' + x + y))
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
, ASN1('04'
|
|
||||||
, ASN1('30'
|
|
||||||
, ASN1.UInt('01')
|
|
||||||
, ASN1('04', d)
|
|
||||||
, ASN1('A1', ASN1.BitStr('04' + x + y)))))
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
x509.packSpki = function (jwk) {
|
x509.packSpki = function(jwk) {
|
||||||
if (/EC/i.test(jwk.kty)) {
|
if (/EC/i.test(jwk.kty)) {
|
||||||
return x509.packSpkiEc(jwk);
|
return x509.packSpkiEc(jwk);
|
||||||
}
|
}
|
||||||
return x509.packSpkiRsa(jwk);
|
return x509.packSpkiRsa(jwk);
|
||||||
};
|
};
|
||||||
x509.packSpkiRsa = function (jwk) {
|
x509.packSpkiRsa = function(jwk) {
|
||||||
if (!jwk.d) {
|
if (!jwk.d) {
|
||||||
// Public RSA
|
// Public RSA
|
||||||
return Enc.hexToBuf(ASN1('30'
|
return Enc.hexToBuf(
|
||||||
, ASN1('30'
|
ASN1(
|
||||||
, ASN1('06', '2a864886f70d010101')
|
'30',
|
||||||
, ASN1('05')
|
ASN1('30', ASN1('06', '2a864886f70d010101'), ASN1('05')),
|
||||||
|
ASN1.BitStr(
|
||||||
|
ASN1(
|
||||||
|
'30',
|
||||||
|
ASN1.UInt(Enc.base64ToHex(jwk.n)),
|
||||||
|
ASN1.UInt(Enc.base64ToHex(jwk.e))
|
||||||
)
|
)
|
||||||
, ASN1.BitStr(ASN1('30'
|
)
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.n))
|
)
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.e))
|
);
|
||||||
))
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Private RSA
|
// Private RSA
|
||||||
return Enc.hexToBuf(ASN1('30'
|
return Enc.hexToBuf(
|
||||||
, ASN1.UInt('00')
|
ASN1(
|
||||||
, ASN1('30'
|
'30',
|
||||||
, ASN1('06', '2a864886f70d010101')
|
ASN1.UInt('00'),
|
||||||
, ASN1('05')
|
ASN1('30', ASN1('06', '2a864886f70d010101'), ASN1('05')),
|
||||||
)
|
ASN1(
|
||||||
, ASN1('04'
|
'04',
|
||||||
, ASN1('30'
|
ASN1(
|
||||||
, ASN1.UInt('00')
|
'30',
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.n))
|
ASN1.UInt('00'),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.e))
|
ASN1.UInt(Enc.base64ToHex(jwk.n)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.d))
|
ASN1.UInt(Enc.base64ToHex(jwk.e)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.p))
|
ASN1.UInt(Enc.base64ToHex(jwk.d)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.q))
|
ASN1.UInt(Enc.base64ToHex(jwk.p)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.dp))
|
ASN1.UInt(Enc.base64ToHex(jwk.q)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.dq))
|
ASN1.UInt(Enc.base64ToHex(jwk.dp)),
|
||||||
, ASN1.UInt(Enc.base64ToHex(jwk.qi))
|
ASN1.UInt(Enc.base64ToHex(jwk.dq)),
|
||||||
|
ASN1.UInt(Enc.base64ToHex(jwk.qi))
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
));
|
)
|
||||||
};
|
);
|
||||||
x509.packSpkiEc = function (jwk) {
|
};
|
||||||
|
x509.packSpkiEc = function(jwk) {
|
||||||
var x = Enc.base64ToHex(jwk.x);
|
var x = Enc.base64ToHex(jwk.x);
|
||||||
var y = Enc.base64ToHex(jwk.y);
|
var y = Enc.base64ToHex(jwk.y);
|
||||||
var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
|
var objId = 'P-256' === jwk.crv ? OBJ_ID_EC : OBJ_ID_EC_384;
|
||||||
return Enc.hexToBuf(
|
return Enc.hexToBuf(
|
||||||
ASN1('30'
|
ASN1(
|
||||||
, ASN1('30'
|
'30',
|
||||||
, OBJ_ID_EC_PUB
|
ASN1('30', OBJ_ID_EC_PUB, objId),
|
||||||
, objId
|
ASN1.BitStr('04' + x + y)
|
||||||
)
|
)
|
||||||
, ASN1.BitStr('04' + x + y))
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
x509.packPkix = x509.packSpki;
|
x509.packPkix = x509.packSpki;
|
||||||
|
})('undefined' !== typeof module ? module.exports : window);
|
||||||
}('undefined' !== typeof module ? module.exports : window));
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@bluecrypt/acme",
|
"name": "acme",
|
||||||
"version": "1.0.0",
|
"version": "2.0.0-wip.0",
|
||||||
"lockfileVersion": 1,
|
"lockfileVersion": 1,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
@ -82,6 +82,12 @@
|
||||||
"glob": "^7.1.1"
|
"glob": "^7.1.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"commander": {
|
||||||
|
"version": "2.20.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.1.tgz",
|
||||||
|
"integrity": "sha512-cCuLsMhJeWQ/ZpsFTbE765kvVfoeSddc4nU3up4fV+fDBcfUXnbITJ+JzhkdjzOqhURjZgujxaioam4RM9yGUg==",
|
||||||
|
"dev": true
|
||||||
|
},
|
||||||
"concat-map": {
|
"concat-map": {
|
||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||||
|
@ -509,6 +515,12 @@
|
||||||
"integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==",
|
"integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
|
"source-map": {
|
||||||
|
"version": "0.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
|
||||||
|
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
|
||||||
|
"dev": true
|
||||||
|
},
|
||||||
"statuses": {
|
"statuses": {
|
||||||
"version": "1.4.0",
|
"version": "1.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz",
|
||||||
|
@ -525,6 +537,16 @@
|
||||||
"mime-types": "~2.1.24"
|
"mime-types": "~2.1.24"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"uglify-js": {
|
||||||
|
"version": "3.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.6.0.tgz",
|
||||||
|
"integrity": "sha512-W+jrUHJr3DXKhrsS7NUVxn3zqMOFn0hL/Ei6v0anCIMoKC93TjcflTagwIHLW7SfMFfiQuktQyFVCFHGUE0+yg==",
|
||||||
|
"dev": true,
|
||||||
|
"requires": {
|
||||||
|
"commander": "~2.20.0",
|
||||||
|
"source-map": "~0.6.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"unpipe": {
|
"unpipe": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||||
|
|
12
package.json
12
package.json
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@bluecrypt/acme",
|
"name": "acme",
|
||||||
"version": "1.0.1",
|
"version": "2.0.0-wip.0",
|
||||||
"description": "Free SSL certificates through Let's Encrypt, right in your browser",
|
"description": "Free SSL certificates through Let's Encrypt, right in your browser",
|
||||||
"main": "bluecrypt-acme.js",
|
"main": "bluecrypt-acme.js",
|
||||||
"homepage": "https://rootprojects.org/acme/",
|
"homepage": "https://rootprojects.org/acme/",
|
||||||
|
@ -9,10 +9,11 @@
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib",
|
"lib",
|
||||||
"bluecrypt-acme.js",
|
"dist"
|
||||||
"bluecrypt-acme.min.js"
|
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"build": "node bin/bundle.js",
|
||||||
|
"lint": "jshint lib bin",
|
||||||
"test": "node server.js",
|
"test": "node server.js",
|
||||||
"start": "node server.js"
|
"start": "node server.js"
|
||||||
},
|
},
|
||||||
|
@ -37,6 +38,7 @@
|
||||||
"@root/request": "^1.3.10",
|
"@root/request": "^1.3.10",
|
||||||
"dig.js": "^1.3.9",
|
"dig.js": "^1.3.9",
|
||||||
"dns-suite": "^1.2.12",
|
"dns-suite": "^1.2.12",
|
||||||
"express": "^4.16.4"
|
"express": "^4.16.4",
|
||||||
|
"uglify-js": "^3.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue