JSEncrypt加密后Node-Forge解密报错:Encrypted message length is invalid
问题解决:JSEncrypt与Node-Forge RSA加解密兼容问题
核心原因
JSEncrypt默认使用RSA-PKCS1-v1_5填充方案,而你后端Node-Forge代码中默认/指定的是RSA-OAEP填充,两者不匹配导致解密时出现长度校验错误。此外,JSEncrypt加密输出为Base64字符串,Node-Forge解密时需要先解码为字节数组才能处理。
解决方案
方案1:后端适配JSEncrypt默认的PKCS1填充
无需修改前端代码,只需调整Node-Forge的解密逻辑:
const encrypt = new JSEncrypt(); encrypt.setPublicKey(publicKey); let encrypedQuery = encrypt.encrypt(message); console.log(encrypedQuery); try{ const privateK = forge.pki.privateKeyFromPem(privateKey); // 将JSEncrypt输出的Base64字符串解码为字节数组 const encryptedBytes = forge.util.decode64(encrypedQuery); // 指定PKCS1填充解密(匹配JSEncrypt默认行为) const decrypted2 = privateK.decrypt(encryptedBytes, 'RSA-PKCS1'); console.log('original:', decrypted2); }catch(err){ console.log(err); }
方案2:统一使用更安全的RSA-OAEP填充(推荐)
修改前端JSEncrypt逻辑,启用OAEP填充,与后端原有解密逻辑兼容:
const encrypt = new JSEncrypt(); encrypt.setPublicKey(publicKey); // 获取底层RSA实例,设置OAEP填充方案 const rsaInstance = encrypt.getKey(); rsaInstance.setOptions({ encryptionScheme: 'oaep' }); let encrypedQuery = encrypt.encrypt(message); console.log(encrypedQuery); // 后端解密逻辑保持原有OAEP配置即可 try{ const privateK = forge.pki.privateKeyFromPem(privateKey); const encryptedBytes = forge.util.decode64(encrypedQuery); const decrypted2 = privateK.decrypt(encryptedBytes, 'RSA-OAEP'); console.log('original:', decrypted2); }catch(err){ console.log(err); }
内容的提问来源于stack exchange,提问作者user824624
相关产品推荐
相关产品推荐

