UNPKG

@meeco/cryppo

Version:

In-browser encryption and decryption. Clone of Ruby Cryppo

55 lines 2.12 kB
import forge from 'node-forge'; import { SerializationFormat } from '../serialization-versions.js'; import { deSerialize, keyLengthFromPublicKeyPem, serialize } from '../util.js'; const { pki } = forge; export 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, }); }); }); } export function encryptPrivateKeyWithPassword({ privateKeyPem, password, }) { const privateKey = pki.privateKeyFromPem(privateKeyPem); return pki.encryptRsaPrivateKey(privateKey, password); } export async function encryptWithPublicKey({ publicKeyPem, data, scheme = 'RSA-OAEP', }, serializationFormat = SerializationFormat.latest_version) { const pk = pki.publicKeyFromPem(publicKeyPem); const encrypted = pk.encrypt(data, scheme); const bitLength = keyLengthFromPublicKeyPem(publicKeyPem); const serialized = serialize(`Rsa${bitLength}`, encrypted, {}, serializationFormat); return { encrypted, serialized, }; } // compatiblity not tested with other cryppo // | 'RSAES-PKCS1-V1_5' // | 'RSA-OAEP' // | 'RAW' // | 'NONE' // | null // | undefined; export async function decryptSerializedWithPrivateKey({ password, privateKeyPem, serialized, scheme = 'RSA-OAEP', }) { const encrypted = deSerialize(serialized).decodedPairs[0]; return decryptWithPrivateKey({ password, privateKeyPem, encrypted, scheme, }); } export async function decryptWithPrivateKey({ password, privateKeyPem, encrypted, scheme = 'RSA-OAEP', }) { const pk = pki.decryptRsaPrivateKey(privateKeyPem, password); return pk.decrypt(encrypted, scheme); } //# sourceMappingURL=rsa.js.map