jsencrypt Message too long for RSA

875 阅读1分钟

此问题是需要加密的字符串过大,拆分加密后即可解决

import JSEncrypt from 'jsencrypt';

const plaintext = '...'//要被加密的明文
const encrypt = new JSEncrypt();
encrypt.setPublicKey(
`-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----`);

const encrypted = splitPlaintext(encrypt, plaintext);
const splitPlaintext =(encrypt, plaintext)=>{
    // 分割长度默认是32
    const len = 32;
    // 小于32不必分割
    if (plaintext.length < len) {
        return encrypt.decrypt(plaintext);
    }
    const result = [];
    // 当前的明文最多能分割成多少份
    const splitCount = Math.ceil(plaintext.length / len);
    // 循环分割
    for (let i = 0; i < splitCount; i++) {
        result.push(plaintext.substring(i * len, (i + 1) * len));
    }
    // 结果拼回字符串
    return result.map((str) => encrypt.decrypt(plaintext)).join('');
}