@meeco/cryppo
Version:
In-browser encryption and decryption. Clone of Ruby Cryppo
65 lines • 2.69 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateRSAKeyPair = generateRSAKeyPair;
exports.encryptPrivateKeyWithPassword = encryptPrivateKeyWithPassword;
exports.encryptWithPublicKey = encryptWithPublicKey;
exports.decryptSerializedWithPrivateKey = decryptSerializedWithPrivateKey;
exports.decryptWithPrivateKey = decryptWithPrivateKey;
const node_forge_1 = __importDefault(require("node-forge"));
const serialization_versions_js_1 = require("../serialization-versions.js");
const util_js_1 = require("../util.js");
const { pki } = node_forge_1.default;
function generateRSAKeyPair(bits = 4096) {
return new Promise((resolve, reject) => {
// -1 workers to estimate number of cores available
// https://github.com/digitalbazaar/forge#rsa
pki.rsa.generateKeyPair({ bits, workers: 0 }, (err, keyPair) => {
if (err) {
return reject(err);
}
resolve({
privateKey: pki.privateKeyToPem(keyPair.privateKey),
publicKey: pki.publicKeyToPem(keyPair.publicKey),
bits,
});
});
});
}
function encryptPrivateKeyWithPassword({ privateKeyPem, password, }) {
const privateKey = pki.privateKeyFromPem(privateKeyPem);
return pki.encryptRsaPrivateKey(privateKey, password);
}
async function encryptWithPublicKey({ publicKeyPem, data, scheme = 'RSA-OAEP', }, serializationFormat = serialization_versions_js_1.SerializationFormat.latest_version) {
const pk = pki.publicKeyFromPem(publicKeyPem);
const encrypted = pk.encrypt(data, scheme);
const bitLength = (0, util_js_1.keyLengthFromPublicKeyPem)(publicKeyPem);
const serialized = (0, util_js_1.serialize)(`Rsa${bitLength}`, encrypted, {}, serializationFormat);
return {
encrypted,
serialized,
};
}
// compatiblity not tested with other cryppo
// | 'RSAES-PKCS1-V1_5'
// | 'RSA-OAEP'
// | 'RAW'
// | 'NONE'
// | null
// | undefined;
async function decryptSerializedWithPrivateKey({ password, privateKeyPem, serialized, scheme = 'RSA-OAEP', }) {
const encrypted = (0, util_js_1.deSerialize)(serialized).decodedPairs[0];
return decryptWithPrivateKey({
password,
privateKeyPem,
encrypted,
scheme,
});
}
async function decryptWithPrivateKey({ password, privateKeyPem, encrypted, scheme = 'RSA-OAEP', }) {
const pk = pki.decryptRsaPrivateKey(privateKeyPem, password);
return pk.decrypt(encrypted, scheme);
}
//# sourceMappingURL=rsa.js.map