1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
'use strict';
const crypto = require('crypto'); const constants = require('constants'); const _padding = constants.RSA_PKCS1_PADDING; const _encoding = 'base64'; const _signatureAlgorithm = 'RSA-SHA1';
class XxxxRSA { constructor(options) { this.options = Object.assign({}, options); }
_sign(data) { const sign = crypto.createSign(_signatureAlgorithm); sign.update(data, 'utf8'); return sign.sign(this.options.privateKey, _encoding); }
_verify(sign, data) { const verifier = crypto.createVerify(_signatureAlgorithm); verifier.update(new Buffer(data, _encoding), 'utf8'); return verifier.verify(this.options.publicKey, new Buffer(sign, _encoding)); }
encrypt(msg) { const blockSize = 128; const padding = 11;
let buffer = new Buffer(msg);
const chunkSize = blockSize - padding; const nbBlocks = Math.ceil(buffer.length / (chunkSize));
let outputBuffer = new Buffer(nbBlocks * blockSize); for (let i = 0; i < nbBlocks; i++) { let currentBlock = buffer.slice(chunkSize * i, chunkSize * (i + 1)); let encryptedChunk = crypto.publicEncrypt({ key: this.options.publicKey, padding: _padding }, currentBlock);
encryptedChunk.copy(outputBuffer, i * blockSize); }
return { data: outputBuffer.toString(_encoding), sign: this._sign(outputBuffer) }; };
decrypt(obj) { if (!this._verify(obj.sign, obj.data)) { throw new Error('Sign verify field.'); }
const blockSize = 128; let buffer = new Buffer(obj.data, _encoding); const nbBlocks = Math.ceil(buffer.length / (blockSize)); let outputBuffer = new Buffer(nbBlocks * blockSize);
let totalLength = 0; for (var i = 0; i < nbBlocks; i++) { let currentBlock = buffer.slice(blockSize * i, Math.min(blockSize * (i + 1), buffer.length)); let decryptedBuf = crypto.privateDecrypt({ key: this.options.privateKey, padding: _padding }, currentBlock);
decryptedBuf.copy(outputBuffer, totalLength); totalLength += decryptedBuf.length; }
let data = outputBuffer.slice(0, totalLength);
return data.toString(); }; }
export default XxxxRSA;
|