UNPKG

@bogdan-nita/netopia-card

Version:
39 lines (31 loc) 1.24 kB
const forge = require('node-forge'); const rc4 = require('./arc4'); // Helper function to check if a string is base64 encoded const isBase64 = (str) => { try { return Buffer.from(str, 'base64').toString('base64') === str; } catch (err) { return false; } }; const decrypt = (privateKeyPem, envKey, data) => { try { // Parse the private key from PEM format const privateKey = forge.pki.privateKeyFromPem(privateKeyPem); // Decode envKey from base64 or utf-8 as needed const envBuffer = isBase64(envKey) ? Buffer.from(envKey, 'base64') : Buffer.from(envKey, 'utf8'); // Decrypt the envKey using PKCS#1 v1.5 const decryptedKey = privateKey.decrypt(envBuffer.toString('binary'), 'RSAES-PKCS1-V1_5'); // Initialize RC4 with the decrypted key const cipher = rc4(decryptedKey); // Decode data if it's base64, otherwise treat as utf-8 const dataBuffer = isBase64(data) ? Buffer.from(data, 'base64') : Buffer.from(data, 'utf8'); return cipher.decode(dataBuffer, 'utf8'); } catch (error) { console.error('Decryption error:', error); throw new Error('Decryption failed. Ensure the private key and data formats are correct.'); } }; module.exports = decrypt;