diff --git a/src/ssn/extractFileStream.ts b/src/ssn/extractFileStream.ts index 7298329..59b5e79 100644 --- a/src/ssn/extractFileStream.ts +++ b/src/ssn/extractFileStream.ts @@ -37,8 +37,8 @@ export default function extractFileStream(file: ISsnFileEntry, inputStream: stre //pipe into decryption if file is encrypted if (file.decryptionKeys !== undefined) { - const decryptTransform = decryptStream(curStream, [...file.decryptionKeys] as [number, number, number]); - curStream = decryptTransform; + const decryptTransform = decryptStream([...file.decryptionKeys] as [number, number, number]); + curStream = curStream.pipe(decryptTransform); } //pipe into decompression @@ -46,8 +46,7 @@ export default function extractFileStream(file: ISsnFileEntry, inputStream: stre decompressTransform.on('error', (error) => { throw new Error(`Error during decompression: ${error.message}`); }); - curStream.pipe(decompressTransform); - curStream = decompressTransform; + curStream = curStream.pipe(decompressTransform); //set max length const maxLength2 = streamSetMaxLength(curStream, file.size); diff --git a/src/ssn/streams/decryptStream.ts b/src/ssn/streams/decryptStream.ts index 1c31c5b..26ed865 100644 --- a/src/ssn/streams/decryptStream.ts +++ b/src/ssn/streams/decryptStream.ts @@ -1,26 +1,22 @@ import * as stream from 'stream'; import getDecryptor from '../decryption/decryptChunk'; -export default function decryptStream(inputStream: stream.Readable, decryptionKeys: [number, number, number]): stream.Readable { +export default function decryptTransform(decryptionKeys: [number, number, number]): stream.Transform { const decryptor = getDecryptor(decryptionKeys); + const transform = new stream.Transform(); - const outStream = new stream.Readable({ - read(size) { - //Decrypt chunk - const encryptedChunk: Buffer = inputStream.read(size); - if (encryptedChunk === null) { - //If end has been reached, stop - this.push(null); - } else { - const decryptedChunk = decryptor(encryptedChunk); - this.push(decryptedChunk); - } - }, + transform.on('readable', () => { + const encryptedChunk = transform.read(); + + if (encryptedChunk === null) { + transform.end(); + return; + } + + const decryptedChunk = decryptor(encryptedChunk); + + transform.write(decryptedChunk); }); - inputStream.on('end', () => { - outStream.emit('end'); - }); - - return outStream; + return transform; }