长字符串加密

22 阅读1分钟

`import forge from 'node-forge';

import {Base64} from "js-base64";

export function encryptByPublicKey(qurey) {

let str = ''

if (typeof qurey == 'string') {

str = qurey;

} else {

str = JSON.stringify(qurey)

}

let base64str = Base64.encode(str)

const MAX_ENCRYPT_BLOCK = 117;

const publicKey = '';

const pemPublicKey = -----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----;

const pubKey = forge.pki.publicKeyFromPem(pemPublicKey);

let encrypted = '';

let offSet = 0;

const inputLen = base64str.length;

while (inputLen - offSet > 0) {

let end = offSet + MAX_ENCRYPT_BLOCK;

if (end > inputLen) {

end = inputLen;

}

const chunk = base64str.substring(offSet, end);

const encryptedChunk = pubKey.encrypt(chunk, 'RSAES-PKCS1-V1_5');

encrypted += encryptedChunk;

offSet += MAX_ENCRYPT_BLOCK;

}

return forge.util.encode64(encrypted);

}`