RSACipher.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const forge = require('node-forge');
  2. const base64 = require('base64-js');
  3. class RSACipher {
  4. /**
  5. * RSA Decryption
  6. * @param {string} privateKey - The private key in PEM format
  7. * @param {string} msg - The message to decrypt, encoded in base64
  8. * @returns {string} - The decrypted message
  9. */
  10. longDecrypt(privateKey, msg) {
  11. // Format the private key
  12. privateKey = `-----BEGIN RSA PRIVATE KEY-----\n${privateKey.match(/.{1,64}/g).join('\n')}\n-----END RSA PRIVATE KEY-----\n`;
  13. // Decode the base64 message
  14. const encryptedBytes = base64.toByteArray(msg);
  15. // Convert private key from PEM to forge object
  16. const privateKeyObj = forge.pki.privateKeyFromPem(privateKey);
  17. // Decrypt the message
  18. let decrypted = '';
  19. const blockSize = 128; // 128 bytes block size
  20. for (let i = 0; i < encryptedBytes.length; i += blockSize) {
  21. const block = encryptedBytes.slice(i, i + blockSize);
  22. decrypted += privateKeyObj.decrypt(forge.util.createBuffer(block), 'RSAES-PKCS1-V1_5');
  23. }
  24. return decrypted;
  25. }
  26. /**
  27. * Signature method
  28. * @param {string} privateKey - The private key in PEM format
  29. * @param {string} text - The text to sign
  30. * @returns {string} - Base64 encoded signature
  31. */
  32. sign(privateKey, text) {
  33. // Format the private key
  34. privateKey = `-----BEGIN RSA PRIVATE KEY-----\n${privateKey.match(/.{1,64}/g).join('\n')}\n-----END RSA PRIVATE KEY-----\n`;
  35. // Convert private key from PEM to forge object
  36. const privateKeyObj = forge.pki.privateKeyFromPem(privateKey);
  37. // Create a signature object
  38. const md = forge.md.md5.create();
  39. md.update(text, 'utf8');
  40. const signature = privateKeyObj.sign(md, 'RSA-SHA256');
  41. // Encode the signature in base64
  42. return base64.fromByteArray(signature);
  43. }
  44. }
  45. module.exports = RSACipher;