Описание проблемы
Я столкнулся с проблемой обеспечения согласованный вывод шифрования между Node.js и PHP при чтении больших файлов по частям. Вывод отличается, хотя считываются и обрабатываются одни и те же значения. Ниже приведен код для реализаций PHP и Node.js.
Код PHP
Код: Выделить всё
Код: Выделить всё
const PADDING_BLOCK_SIZE = 16;
const ALGORITHM = "aes-256-cbc";
const PLAINTEXT_DATA_KEY = "poSENHhkGVG/4fEHvhRO6j9W3goETWZAg+ZgTWxhw34=";
const IV = "X1bIRjgIoDn/BDFhHIbg7g=="; // randombytes(16) converted to base64
const CHUNK_SIZE = 16 * 1024;
class Cipher {
private pkcs7Pad(buffer: Buffer, blockSize: number = PADDING_BLOCK_SIZE): Buffer {
const padding = blockSize - (buffer.length % blockSize);
const padBuffer = Buffer.alloc(padding, padding);
return Buffer.concat([buffer, padBuffer]);
}
async encrypt(source: string, dest: string) {
return new Promise(async (res, rej) => {
const iv = base64ToBuffer(IV);
const cipher = createCipheriv(ALGORITHM, base64ToUint8Array(PLAINTEXT_DATA_KEY), iv);
cipher.setAutoPadding(false);
const readStream = createReadStream(source, { highWaterMark: CHUNK_SIZE });
const writeStream = createWriteStream(dest, { highWaterMark: CHUNK_SIZE });
writeStream.write(iv);
let tempChunkStorage = Buffer.alloc(0); // Buffer to store remaining data
readStream.on(DATA_EVENT, (chunk) => {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk);
}
// Append the new chunk to the temp storage
tempChunkStorage = Buffer.concat([tempChunkStorage, chunk]);
while (tempChunkStorage.length >= CHUNK_SIZE) {
const block = tempChunkStorage.subarray(0, CHUNK_SIZE);
const encryptedBuffer = cipher.update(block);
writeStream.write(encryptedBuffer);
tempChunkStorage = tempChunkStorage.subarray(CHUNK_SIZE);
}
});
readStream.on("end", () => {
if (tempChunkStorage.length > 0) {
const encryptedBuffer = cipher.update(this.pkcs7Pad(tempChunkStorage)); // Add padding
writeStream.write(encryptedBuffer);
cipher.final();
}
writeStream.end();
res(true);
});
readStream.on("error", (err) => {
writeStream.close();
rej(err);
});
});
}
}
Код: Выделить всё
First 50 characters of the cipher (base64) in PHP: 0tCb9xtx5KpG+56ukYvcQDoNKCdoPtAFUrFDRc4TiqQrQocQRK
First 50 characters of the cipher (base64) in Node: sUUI4nXHwhKNdRs+Brqc5neKuKb3fx4qqBohlDSn/7FVrYo46/

Подробнее здесь: https://stackoverflow.com/questions/786 ... -reading-l