12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- const forge = require('node-forge');
- const base64 = require('base64-js');
- class RSACipher {
- /**
- * RSA Decryption
- * @param {string} privateKey - The private key in PEM format
- * @param {string} msg - The message to decrypt, encoded in base64
- * @returns {string} - The decrypted message
- */
- longDecrypt(privateKey, msg) {
- // Format the private key
- privateKey = `-----BEGIN RSA PRIVATE KEY-----\n${privateKey.match(/.{1,64}/g).join('\n')}\n-----END RSA PRIVATE KEY-----\n`;
-
- // Decode the base64 message
- const encryptedBytes = base64.toByteArray(msg);
-
- // Convert private key from PEM to forge object
- const privateKeyObj = forge.pki.privateKeyFromPem(privateKey);
- // Decrypt the message
- let decrypted = '';
- const blockSize = 128; // 128 bytes block size
- for (let i = 0; i < encryptedBytes.length; i += blockSize) {
- const block = encryptedBytes.slice(i, i + blockSize);
- decrypted += privateKeyObj.decrypt(forge.util.createBuffer(block), 'RSAES-PKCS1-V1_5');
- }
-
- return decrypted;
- }
- /**
- * Signature method
- * @param {string} privateKey - The private key in PEM format
- * @param {string} text - The text to sign
- * @returns {string} - Base64 encoded signature
- */
- sign(privateKey, text) {
- // Format the private key
- privateKey = `-----BEGIN RSA PRIVATE KEY-----\n${privateKey.match(/.{1,64}/g).join('\n')}\n-----END RSA PRIVATE KEY-----\n`;
- // Convert private key from PEM to forge object
- const privateKeyObj = forge.pki.privateKeyFromPem(privateKey);
-
- // Create a signature object
- const md = forge.md.md5.create();
- md.update(text, 'utf8');
- const signature = privateKeyObj.sign(md, 'RSA-SHA256');
- // Encode the signature in base64
- return base64.fromByteArray(signature);
- }
- }
- module.exports = RSACipher;
|