RSA加解密,可加密的最长明文长度为1024bit,即128字节,但是某段明文长度小于128字节,就需要进行padding,因为如果没有padding,用户无法确分解密后内容的真实长度。由于padding的存在,占用了明文的11字节长度,最后一次能加密的明文长度就变为传说中的117字节。
附上一段运用js的rsa加解密代码:
前端加密:
import { Buffer } from 'buffer'
import { publicEncrypt, constants } from 'crypto'
const publicKey = `-----BEGIN PUBLIC KEY----- xxxxxx -----END PUBLIC KEY-----`
export const encrypt = origin => {
const buffer = Buffer.from(encodeURI(JSON.stringify(origin)))
const blocks = Math.ceil(buffer.length / 117)
const cipherBuffer = Buffer.alloc(blocks * 128)
for (let i = 0; i < blocks; i++) {
const chunk = buffer.slice(i * 117, (i + 1) * 117)
publicEncrypt({
key: publicKey,
padding: constants.RSA_PKCS1_PADDING
}, chunk).copy(cipherBuffer, i * 128)
}
return cipher