使用 zlib 和 cryptojs 加密压缩数据

Encrypt compressed data using zlib and cryptojs

我在节点 js 中,尝试使用 zlib.deflate 压缩 object,然后使用 cryptojs[= 对其进行加密20=] AES.

然后,当我尝试获取原始值时,我在 zlib.inflate 调用中失败并出现错误:"incorrect header检查.

const zlib = require('zlib');
const { AES, enc } = require('crypto-js');

const obj = {
    a: "a",
    b: "b"
};

const inputToDeflate = JSON.stringify(obj);
const compressed = zlib.deflateSync(inputToDeflate);
const encrypted = AES.encrypt(compressed.toString(), 'f11').toString();


const decrypted = AES.decrypt(encrypted, 'f11');
const decompressed = zlib.inflateSync(decrypted.toString(enc.Utf8));

我认为您在加密前将其转换为字符串时丢失了 zlib header。我们需要以某种方式更改此 compressed.toString(),使 header 仍保留在内部,例如 base64 编码。

const buffer = Buffer.from(compressed).toString("base64")
const encrypted = AES.encrypt(buffer, 'f11').toString();

解密提示相同,但​​我们需要像以前一样将结果从 base64 解码回原始 zlib 数据。

const decrypted = AES.decrypt(encrypted, 'f11').toString(enc.Utf8);
const decryptedBuffer = Buffer.from(decrypted,'base64')
const decompressed = zlib.inflateSync(decryptedBuffer);

const resultString = decompressed.toString()

就是这样。但我在这里建议在压缩之前先做加密部分。因为结果字符串不同。看看这个完整的代码:

完整代码

const zlib = require('zlib');
const { AES, enc } = require('crypto-js');

const obj = {
    a: "a",
    b: "b"
};

const inputToDeflate = JSON.stringify(obj);
const compressed = zlib.deflateSync(inputToDeflate);

// Compact the data to base64
const buffer = Buffer.from(compressed).toString("base64")
const encrypted = AES.encrypt(buffer, 'f11').toString();

console.log("compressed + base64 + encrypted length",encrypted.length)

const decrypted = AES.decrypt(encrypted, 'f11').toString(enc.Utf8);

// Convert the result from base64 to original compressed data
const decryptedBuffer = Buffer.from(decrypted,'base64')
const decompressed = zlib.inflateSync(decryptedBuffer);

// Convert buffer to string
const resultString = decompressed.toString()

// vice versa
console.log(resultString)

输出:

compressed + base64 + encrypted length 88
{"a":"a","b":"b"}

建议

const zlib = require('zlib');
const { AES, enc } = require('crypto-js');

const obj = {
    a: "a",
    b: "b"
};

const inputData = JSON.stringify(obj);
const encrypted = AES.encrypt(inputData, 'f11').toString();
const compressed = zlib.deflateSync(encrypted);

console.log("encrypted + compressed length",encrypted.length)

const decompressed = zlib.inflateSync(compressed);
const decrypted = AES.decrypt(decompressed.toString(), 'f11').toString(enc.Utf8);

console.log(decrypted)

输出:

encrypted + compressed length 64
{"a":"a","b":"b"}

我觉得先加密再压缩效率更高