forked from vanielf/pdf-lib
-
Notifications
You must be signed in to change notification settings - Fork 27
/
DecryptStream.ts
56 lines (47 loc) · 1.34 KB
/
DecryptStream.ts
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
import DecodeStream from './DecodeStream';
import { StreamType } from './Stream';
const chunkSize = 512;
type DecryptFnType = (
arg1: Uint8Array | Uint8ClampedArray,
arg2: boolean,
) => Uint8Array;
class DecryptStream extends DecodeStream {
private stream: StreamType;
private initialized: boolean;
private nextChunk: Uint8Array | Uint8ClampedArray | null;
private decrypt: DecryptFnType;
constructor(
stream: StreamType,
decrypt: DecryptFnType,
maybeLength?: number,
) {
super(maybeLength);
this.stream = stream;
this.decrypt = decrypt;
this.nextChunk = null;
this.initialized = false;
}
readBlock() {
let chunk;
if (this.initialized) {
chunk = this.nextChunk;
} else {
chunk = this.stream.getBytes(chunkSize);
this.initialized = true;
}
if (!chunk || chunk.length === 0) {
this.eof = true;
return;
}
this.nextChunk = this.stream.getBytes(chunkSize);
const hasMoreData = this.nextChunk && this.nextChunk.length > 0;
const decrypt = this.decrypt;
chunk = decrypt(chunk, !hasMoreData);
const bufferLength = this.bufferLength;
const newLength = bufferLength + chunk.length;
const buffer = this.ensureBuffer(newLength);
buffer.set(chunk, bufferLength);
this.bufferLength = newLength;
}
}
export default DecryptStream;