js-crypto-key-utils
Version:
Universal Module for Cryptographic Key Utilities in JavaScript, including PEM-JWK converters
390 lines • 20.9 kB
JavaScript
"use strict";
/**
* rfc8081
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decryptEncryptedPrivateKeyInfo = exports.encryptEncryptedPrivateKeyInfo = void 0;
var params = __importStar(require("./params"));
var asn1def_1 = require("./asn1def");
var des_js_1 = __importDefault(require("des.js"));
var BufferMod = __importStar(require("buffer"));
var asn1_js_1 = __importDefault(require("asn1.js"));
var js_encoding_utils_1 = __importDefault(require("js-encoding-utils"));
var js_crypto_pbkdf_1 = __importDefault(require("js-crypto-pbkdf"));
var js_crypto_aes_1 = __importDefault(require("js-crypto-aes"));
var js_crypto_random_1 = __importDefault(require("js-crypto-random"));
var Buffer = BufferMod.Buffer;
var BN = asn1_js_1.default.bignum;
///////////////////////////////////////////////////////////////////
/**
* Generate EncryptedPrivateKeyInfo ASN.1 object.
* @param {DER} binKey - Binary key in DER format.
* @param {AsnEncryptOptionsWithPassphrase} [options={passphrase: ''}] - Encryption options for ASN.1 private key.
* @return {Promise<DER>} - Encrypted private key in DER.
*/
var encryptEncryptedPrivateKeyInfo = function (binKey, options) {
if (options === void 0) { options = { passphrase: '' }; }
return __awaiter(void 0, void 0, void 0, function () {
var kdfAlgorithm, encryptedPBES2, encryptedPBES1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// default params
if (typeof options.algorithm === 'undefined')
options.algorithm = 'pbes2';
if (typeof options.iterationCount === 'undefined')
options.iterationCount = 2048;
if (!(options.algorithm === 'pbes2')) return [3 /*break*/, 2];
if (typeof options.cipher === 'undefined')
options.cipher = 'aes256-cbc';
if (typeof options.prf === 'undefined')
options.prf = 'hmacWithSHA256';
kdfAlgorithm = 'pbkdf2';
return [4 /*yield*/, encryptPBES2(binKey, options.passphrase, kdfAlgorithm, options.prf, options.iterationCount, options.cipher)];
case 1:
encryptedPBES2 = _a.sent();
return [2 /*return*/, encodePBES2(encryptedPBES2)];
case 2: return [4 /*yield*/, encryptPBES1(binKey, options.passphrase, options.algorithm, options.iterationCount)];
case 3:
encryptedPBES1 = _a.sent();
encryptedPBES1.encryptionAlgorithm.algorithm = params.passwordBasedEncryptionSchemes[encryptedPBES1.encryptionAlgorithm.algorithm].oid; // work around
encryptedPBES1.encryptionAlgorithm.parameters = asn1def_1.PBEParameter.encode(encryptedPBES1.encryptionAlgorithm.parameters, 'der');
return [2 /*return*/, asn1def_1.EncryptedPrivateKeyInfo.encode(encryptedPBES1, 'der')];
}
});
});
};
exports.encryptEncryptedPrivateKeyInfo = encryptEncryptedPrivateKeyInfo;
/**
* Decrypt EncryptedPrivateKeyInfo
* @param {Object} epki - Parsed encrypted
* @param {String} passphrase - Passphrase to decyrpt the object.
* @return {Promise<Object>} - Decrypted object.
*/
var decryptEncryptedPrivateKeyInfo = function (epki, passphrase) { return __awaiter(void 0, void 0, void 0, function () {
var decoded;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
decoded = {};
// encryptionAlgorithm.algorithm
decoded.encryptionAlgorithm = {
algorithm: params.getAlgorithmFromOidStrict(epki.encryptionAlgorithm.algorithm, params.passwordBasedEncryptionSchemes)
};
if (decoded.encryptionAlgorithm.algorithm === 'pbes2') {
decoded.encryptionAlgorithm.parameters = decodePBES2(epki.encryptionAlgorithm.parameters);
}
else {
decoded.encryptionAlgorithm.parameters = asn1def_1.PBEParameter.decode(epki.encryptionAlgorithm.parameters, 'der');
}
decoded.encryptedData = epki.encryptedData;
if (!(decoded.encryptionAlgorithm.algorithm === 'pbes2')) return [3 /*break*/, 2];
return [4 /*yield*/, decryptPBES2(decoded, passphrase)];
case 1: return [2 /*return*/, _a.sent()]; // work around
case 2: return [4 /*yield*/, decryptPBES1(decoded, passphrase)];
case 3: return [2 /*return*/, _a.sent()];
}
});
}); };
exports.decryptEncryptedPrivateKeyInfo = decryptEncryptedPrivateKeyInfo;
//////////////////////////////
var encodePBES2 = function (decoded // work around
) {
var epki = { encryptionAlgorithm: {} }; // work around
// algorithm
epki.encryptionAlgorithm.algorithm = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].oid;
// kdf
var kdf = decoded.encryptionAlgorithm.parameters.keyDerivationFunc;
if (kdf.algorithm === 'pbkdf2') {
kdf.parameters.prf.algorithm = params.pbkdf2Prfs[kdf.parameters.prf.algorithm].oid;
kdf.parameters = asn1def_1.PBKDF2Params.encode(kdf.parameters, 'der');
}
else
throw new Error('UnsupportedKDF');
kdf.algorithm = params.keyDerivationFunctions[kdf.algorithm].oid;
// encryptionScheme
var eS = decoded.encryptionAlgorithm.parameters.encryptionScheme;
if (Object.keys(asn1def_1.PBES2ESParams).indexOf(eS.algorithm) >= 0) {
eS.parameters = asn1def_1.PBES2ESParams[eS.algorithm].encode(eS.parameters, 'der');
}
else
throw new Error('UnsupportedCipher');
eS.algorithm = params.encryptionSchemes[eS.algorithm].oid;
// params
epki.encryptionAlgorithm.parameters = asn1def_1.PBES2Params.encode({ keyDerivationFunc: kdf, encryptionScheme: eS }, 'der');
// encoded data
epki.encryptedData = decoded.encryptedData;
return asn1def_1.EncryptedPrivateKeyInfo.encode(epki, 'der');
};
var decodePBES2 = function (rawParams) {
var pbes2Params = asn1def_1.PBES2Params.decode(rawParams, 'der');
// keyDerivationFunc
var kdfAlgorithm = params.getAlgorithmFromOidStrict(pbes2Params.keyDerivationFunc.algorithm, params.keyDerivationFunctions);
var iterationCount;
var salt;
var prf;
if (kdfAlgorithm === 'pbkdf2') {
var pbkdf2Params = asn1def_1.PBKDF2Params.decode(pbes2Params.keyDerivationFunc.parameters, 'der');
prf = {
algorithm: params.getAlgorithmFromOidStrict(pbkdf2Params.prf.algorithm, params.pbkdf2Prfs),
parameters: pbkdf2Params.prf.parameters
};
iterationCount = pbkdf2Params.iterationCount;
salt = { type: pbkdf2Params.salt.type, value: pbkdf2Params.salt.value };
}
else
throw new Error('UnsupportedKDF');
//encryptionScheme
var encryptionScheme = params.getAlgorithmFromOidStrict(pbes2Params.encryptionScheme.algorithm, params.encryptionSchemes);
var encryptionParams;
if (Object.keys(asn1def_1.PBES2ESParams).indexOf(encryptionScheme) >= 0) {
encryptionParams = asn1def_1.PBES2ESParams[encryptionScheme].decode(pbes2Params.encryptionScheme.parameters, 'der');
}
else
throw new Error('UnsupportedCipher'); // TODO: Other Encryption Scheme
return {
keyDerivationFunc: {
algorithm: kdfAlgorithm,
parameters: { salt: salt, iterationCount: iterationCount, prf: prf }
},
encryptionScheme: {
algorithm: encryptionScheme,
parameters: encryptionParams
}
};
};
//////////////////////
// PBES2 RFC8018 Section 6.2.1
var encryptPBES2 = function (binKey, passphrase, kdfAlgorithm, prf, iterationCount, cipher) { return __awaiter(void 0, void 0, void 0, function () {
var pBuffer, salt, keyLength, key, iv, encryptedData, _a, _b, CBC, ct, _c, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
pBuffer = js_encoding_utils_1.default.encoder.stringToArrayBuffer(passphrase);
return [4 /*yield*/, js_crypto_random_1.default.getRandomBytes(params.keyDerivationFunctions[kdfAlgorithm].defaultSaltLen)];
case 1:
salt = _e.sent();
keyLength = params.encryptionSchemes[cipher].keyLength;
if (!(kdfAlgorithm === 'pbkdf2')) return [3 /*break*/, 3];
return [4 /*yield*/, js_crypto_pbkdf_1.default.pbkdf2(pBuffer, salt, iterationCount, keyLength, params.pbkdf2Prfs[prf].hash)];
case 2:
key = _e.sent(); // work around
return [3 /*break*/, 4];
case 3: throw new Error('UnsupportedKDF');
case 4:
if (!(cipher === 'des-ede3-cbc')) return [3 /*break*/, 6];
_b = (_a = Buffer).from;
return [4 /*yield*/, js_crypto_random_1.default.getRandomBytes(params.encryptionSchemes[cipher].ivLength)];
case 5:
iv = _b.apply(_a, [_e.sent()]);
CBC = des_js_1.default.CBC.instantiate(des_js_1.default.EDE);
ct = CBC.create({ type: 'encrypt', key: Buffer.from(key), iv: iv });
encryptedData = Buffer.from(ct.update(binKey).concat(ct.final()));
return [3 /*break*/, 10];
case 6:
if (!(cipher === 'aes128-cbc' || cipher === 'aes192-cbc' || cipher === 'aes256-cbc')) return [3 /*break*/, 9];
return [4 /*yield*/, js_crypto_random_1.default.getRandomBytes(params.encryptionSchemes[cipher].ivLength)];
case 7:
iv = _e.sent();
_d = (_c = Buffer).from;
return [4 /*yield*/, js_crypto_aes_1.default.encrypt(new Uint8Array(binKey), key, { name: 'AES-CBC', iv: iv })];
case 8:
encryptedData = _d.apply(_c, [_e.sent()]);
iv = Buffer.from(iv);
return [3 /*break*/, 10];
case 9: throw new Error('UnsupportedCipher');
case 10:
// structure
return [2 /*return*/, {
encryptedData: encryptedData,
encryptionAlgorithm: {
algorithm: 'pbes2',
parameters: {
keyDerivationFunc: {
algorithm: kdfAlgorithm,
parameters: {
salt: { type: 'specified', value: Buffer.from(salt) },
iterationCount: new BN(iterationCount),
prf: { algorithm: prf, parameters: Buffer.from([0x05, 0x00]) }
}
},
encryptionScheme: { algorithm: cipher, parameters: iv }
}
}
}];
}
});
}); };
//////////////////////////////
// PBES2 RFC8018 Section 6.2.2
var decryptPBES2 = function (decoded, passphrase) { return __awaiter(void 0, void 0, void 0, function () {
var kdf, eS, keyLength, key, pBuffer, salt, iterationCount, prf, out, iv, CBC, pt, iv, _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
kdf = decoded.encryptionAlgorithm.parameters.keyDerivationFunc;
eS = decoded.encryptionAlgorithm.parameters.encryptionScheme;
keyLength = params.encryptionSchemes[eS.algorithm].keyLength;
if (!(kdf.algorithm === 'pbkdf2')) return [3 /*break*/, 2];
pBuffer = js_encoding_utils_1.default.encoder.stringToArrayBuffer(passphrase);
if (kdf.parameters.salt.type !== 'specified')
throw new Error('UnsupportedSaltSource');
salt = new Uint8Array(kdf.parameters.salt.value);
iterationCount = kdf.parameters.iterationCount.toNumber();
prf = kdf.parameters.prf.algorithm;
return [4 /*yield*/, js_crypto_pbkdf_1.default.pbkdf2(pBuffer, salt, iterationCount, keyLength, params.pbkdf2Prfs[prf].hash)];
case 1:
key = _c.sent();
return [3 /*break*/, 3];
case 2: throw new Error('UnsupportedKDF');
case 3:
if (!(eS.algorithm === 'des-ede3-cbc')) return [3 /*break*/, 4];
iv = eS.parameters;
CBC = des_js_1.default.CBC.instantiate(des_js_1.default.EDE);
pt = CBC.create({ type: 'decrypt', key: key, iv: iv });
out = Buffer.from(pt.update(decoded.encryptedData).concat(pt.final()));
return [3 /*break*/, 7];
case 4:
if (!(eS.algorithm === 'aes128-cbc' || eS.algorithm === 'aes192-cbc' || eS.algorithm === 'aes256-cbc')) return [3 /*break*/, 6];
iv = new Uint8Array(eS.parameters);
_b = (_a = Buffer).from;
return [4 /*yield*/, js_crypto_aes_1.default.decrypt(new Uint8Array(decoded.encryptedData), key, { name: 'AES-CBC', iv: iv })];
case 5:
out = _b.apply(_a, [_c.sent()]);
return [3 /*break*/, 7];
case 6: throw new Error('UnsupportedEncryptionAlgorithm');
case 7: return [2 /*return*/, asn1def_1.OneAsymmetricKey.decode(out, 'der')];
}
});
}); };
//////////////////////////////
// PBES1 RFC8018 Section 6.1.1
var encryptPBES1 = function (binKey, passphrase, algorithm, iterationCount) { return __awaiter(void 0, void 0, void 0, function () {
var pBuffer, salt, hash, keyIv, key, iv, encrypt, out, CBC, ct;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
pBuffer = js_encoding_utils_1.default.encoder.stringToArrayBuffer(passphrase);
return [4 /*yield*/, js_crypto_random_1.default.getRandomBytes(8)];
case 1:
salt = _a.sent();
hash = params.passwordBasedEncryptionSchemes[algorithm].hash;
return [4 /*yield*/, js_crypto_pbkdf_1.default.pbkdf1(pBuffer, salt, iterationCount, 16, hash)];
case 2:
keyIv = _a.sent();
key = keyIv.slice(0, 8);
iv = keyIv.slice(8, 16);
encrypt = params.passwordBasedEncryptionSchemes[algorithm].encrypt;
// TODO: Other Encryption Scheme
if (encrypt === 'DES-CBC') {
CBC = des_js_1.default.CBC.instantiate(des_js_1.default.DES);
ct = CBC.create({ type: 'encrypt', key: key, iv: iv });
out = Buffer.from(ct.update(binKey).concat(ct.final()));
}
else
throw new Error('UnsupportedEncryptionAlgorithm');
return [2 /*return*/, {
encryptionAlgorithm: {
algorithm: algorithm,
parameters: {
salt: Buffer.from(salt),
iterationCount: new BN(iterationCount)
}
},
encryptedData: out
}];
}
});
}); };
//////////////////////////////
// PBES1 RFC8018 Section 6.1.2
var decryptPBES1 = function (decoded, passphrase) { return __awaiter(void 0, void 0, void 0, function () {
var pBuffer, salt, hash, iterationCount, keyIv, key, iv, encrypt, out, CBC, ct;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
pBuffer = js_encoding_utils_1.default.encoder.stringToArrayBuffer(passphrase);
salt = new Uint8Array(decoded.encryptionAlgorithm.parameters.salt);
hash = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].hash;
iterationCount = decoded.encryptionAlgorithm.parameters.iterationCount.toNumber();
return [4 /*yield*/, js_crypto_pbkdf_1.default.pbkdf1(pBuffer, salt, iterationCount, 16, hash)];
case 1:
keyIv = _a.sent();
key = keyIv.slice(0, 8);
iv = keyIv.slice(8, 16);
encrypt = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].encrypt;
// TODO: Other Encryption Scheme
if (encrypt === 'DES-CBC') {
CBC = des_js_1.default.CBC.instantiate(des_js_1.default.DES);
ct = CBC.create({ type: 'decrypt', key: key, iv: iv });
out = Buffer.from(ct.update(decoded.encryptedData).concat(ct.final()));
}
else
throw new Error('UnsupportedEncryptionAlgorithm');
return [2 /*return*/, asn1def_1.OneAsymmetricKey.decode(out, 'der')];
}
});
}); };
//# sourceMappingURL=rfc8018.js.map