马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
目次
目标
环境
实现RSA加解密
盘算RSA加密答应的最大字节长度
目标
- 使用JS实现RSA加密解密。
- 盘算RSA加密答应的最大字节长度。
环境
node-rsa
实现RSA加解密
- const NodeRSA = require('node-rsa');
- function getKey() {
- const keyLength=512
- // 创建 RSA 密钥对
- const key = new NodeRSA({b: keyLength}); // 512位密钥长度(你可以根据需要增加位数)
- const publicKey = key.exportKey('public');
- const privateKey = key.exportKey('private');
- return {
- "publicKey": publicKey,
- "privateKey": privateKey
- };
- }
- /**
- * 加密函数
- * @param plaintext 明文
- * @param publicKey 公钥
- * @returns {string|Buffer} 加密后的数据(Base64 编码)
- */
- function encrypt(plaintext, publicKey) {
- const key = new NodeRSA(publicKey);
- // 使用 PKCS#1 v1.5 填充加密,并返回 Base64 编码
- return key.encrypt(plaintext, 'base64', {encryptionScheme: 'pkcs1'});
- }
- /**
- * 解密函数
- * @param encryptedData 密文
- * @param privateKey 私钥
- * @returns {string} 解密后的明文
- */
- function decrypt(encryptedData, privateKey) {
- const key = new NodeRSA(privateKey);
- // 使用 PKCS#1 v1.5 填充解密
- return key.decrypt(encryptedData, 'utf8', {encryptionScheme: 'pkcs1'});
- }
- // 获取公钥和私钥
- const keyObject = getKey();
- // 输出公钥和私钥
- console.log("公钥:\n", keyObject.publicKey);
- console.log("私钥:\n", keyObject.privateKey);
- // 要加密的明文
- const plaintext = "hello world! 你好";
- // 加密
- const encryptData = encrypt(plaintext, keyObject.publicKey);
- console.log("加密结果:", encryptData);
- // 解密
- const decryptData = decrypt(encryptData, keyObject.privateKey);
- console.log("解密结果:", decryptData);
复制代码 盘算RSA加密答应的最大字节长度
- function getMaxEncryptableBytes(keyLength, paddingType) {
- // 将密钥长度从位转换为字节,就是除以8。
- const keyLengthInBytes = keyLength >> 3;
- // 根据填充类型决定填充长度
- let paddingLength = 0;
- switch (paddingType.toUpperCase()) {
- case 'PKCS1':
- paddingLength = 11; // PKCS#1 v1.5 填充
- break;
- case 'OAEP':
- paddingLength = 42; // OAEP 填充
- break;
- case 'PSS':
- paddingLength = 42; // PSS 填充(假设)
- break;
- case 'NONE':
- paddingLength = 0; // 无填充
- break;
- default:
- throw new Error('未知的填充类型');
- }
- // 计算最大可加密字节数
- return keyLengthInBytes - paddingLength;
- }
- console.log(getMaxEncryptableBytes(512,"PKCS1"))
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |