node-forge Error: Message is too long for PKCS#1 v1.5 padding.

390 阅读1分钟

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

import forge from 'node-forge';

const plaintext = '...'//要被加密的明文
const publicKey = forge.pki.publicKeyFromPem(
`-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----`);
const encrypted = splitPlaintext(publicKey, plaintext);
const splitPlaintext =(publicKey, plaintext)=>{
	// 分割长度默认是32
  	const len = 32;
	// 小于32不必分割
    if (plaintext.length < len) {
        return forge.util.bytesToHex(publicKey.encrypt(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) => forge.util.bytesToHex(publicKey.encrypt(str))).join('');
}