JS实现RSA加密

[复制链接]
发表于 2025-9-23 01:41:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
目次
目标
环境
实现RSA加解密
盘算RSA加密答应的最大字节长度

目标


  • 使用JS实现RSA加密解密。
  • 盘算RSA加密答应的最大字节长度。

环境

        node-rsa

实现RSA加解密

  1. const NodeRSA = require('node-rsa');
  2. function getKey() {
  3.     const keyLength=512
  4.     // 创建 RSA 密钥对
  5.     const key = new NodeRSA({b: keyLength}); // 512位密钥长度(你可以根据需要增加位数)
  6.     const publicKey = key.exportKey('public');
  7.     const privateKey = key.exportKey('private');
  8.     return {
  9.         "publicKey": publicKey,
  10.         "privateKey": privateKey
  11.     };
  12. }
  13. /**
  14. * 加密函数
  15. * @param plaintext 明文
  16. * @param publicKey 公钥
  17. * @returns {string|Buffer} 加密后的数据(Base64 编码)
  18. */
  19. function encrypt(plaintext, publicKey) {
  20.     const key = new NodeRSA(publicKey);
  21.     // 使用 PKCS#1 v1.5 填充加密,并返回 Base64 编码
  22.     return key.encrypt(plaintext, 'base64', {encryptionScheme: 'pkcs1'});
  23. }
  24. /**
  25. * 解密函数
  26. * @param encryptedData 密文
  27. * @param privateKey 私钥
  28. * @returns {string} 解密后的明文
  29. */
  30. function decrypt(encryptedData, privateKey) {
  31.     const key = new NodeRSA(privateKey);
  32.     // 使用 PKCS#1 v1.5 填充解密
  33.     return key.decrypt(encryptedData, 'utf8', {encryptionScheme: 'pkcs1'});
  34. }
  35. // 获取公钥和私钥
  36. const keyObject = getKey();
  37. // 输出公钥和私钥
  38. console.log("公钥:\n", keyObject.publicKey);
  39. console.log("私钥:\n", keyObject.privateKey);
  40. // 要加密的明文
  41. const plaintext = "hello world! 你好";
  42. // 加密
  43. const encryptData = encrypt(plaintext, keyObject.publicKey);
  44. console.log("加密结果:", encryptData);
  45. // 解密
  46. const decryptData = decrypt(encryptData, keyObject.privateKey);
  47. console.log("解密结果:", decryptData);
复制代码

盘算RSA加密答应的最大字节长度

  1. function getMaxEncryptableBytes(keyLength, paddingType) {
  2.     // 将密钥长度从位转换为字节,就是除以8。
  3.     const keyLengthInBytes = keyLength >> 3;
  4.     // 根据填充类型决定填充长度
  5.     let paddingLength = 0;
  6.     switch (paddingType.toUpperCase()) {
  7.         case 'PKCS1':
  8.             paddingLength = 11; // PKCS#1 v1.5 填充
  9.             break;
  10.         case 'OAEP':
  11.             paddingLength = 42; // OAEP 填充
  12.             break;
  13.         case 'PSS':
  14.             paddingLength = 42; // PSS 填充(假设)
  15.             break;
  16.         case 'NONE':
  17.             paddingLength = 0;  // 无填充
  18.             break;
  19.         default:
  20.             throw new Error('未知的填充类型');
  21.     }
  22.     // 计算最大可加密字节数
  23.     return keyLengthInBytes - paddingLength;
  24. }
  25. console.log(getMaxEncryptableBytes(512,"PKCS1"))
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表