|
1 | 1 | import * as crypto from "crypto";
|
| 2 | +import {Algorithm} from "./algorithm.enum"; |
2 | 3 | import {base64EncodedBufferFromString} from "./buffer.function";
|
3 |
| -import {getAlgorithm} from "./get-algorithm.function"; |
| 4 | +import {CipherSpec, getCipherSpec} from "./get-cipher-spec.function"; |
4 | 5 |
|
5 |
| -export const decrypt = async (encrypted: string, secret: string) => { |
6 |
| - const cipherSpec = getAlgorithm(secret); |
| 6 | +interface DecryptInput { |
| 7 | + iv: Buffer; |
| 8 | + content: Buffer; |
| 9 | +} |
| 10 | + |
| 11 | +const sliceInput = (plainInput: Buffer, cipherSpec: CipherSpec): DecryptInput => { |
| 12 | + const iv = plainInput.slice(0, cipherSpec.blockSize); |
| 13 | + const content = plainInput.slice(cipherSpec.blockSize); |
| 14 | + |
| 15 | + return ({ |
| 16 | + content, |
| 17 | + iv |
| 18 | + }); |
| 19 | +}; |
| 20 | + |
| 21 | +export const decrypt = async (encrypted: string, secret: string, algorithm: Algorithm, useIV: boolean = true) => { |
| 22 | + const cipherSpec = getCipherSpec(algorithm); |
7 | 23 | const key = base64EncodedBufferFromString(secret);
|
8 | 24 | const plainInput = base64EncodedBufferFromString(encrypted);
|
9 | 25 |
|
10 |
| - if (plainInput.length < cipherSpec.blockSize) { |
| 26 | + if (useIV && plainInput.length < cipherSpec.blockSize) { |
11 | 27 | throw new Error(`Invalid IV size. Size of ${cipherSpec.blockSize} byte required.`);
|
12 | 28 | }
|
13 | 29 |
|
14 |
| - const iv = plainInput.slice(0, cipherSpec.blockSize); |
15 |
| - const content = plainInput.slice(cipherSpec.blockSize); |
| 30 | + let decipher: crypto.Decipher; |
| 31 | + let data: DecryptInput; |
| 32 | + if (useIV) { |
| 33 | + data = sliceInput(plainInput, cipherSpec); |
16 | 34 |
|
17 |
| - const decipher = crypto.createDecipheriv( |
18 |
| - cipherSpec.cipher, |
19 |
| - key, |
20 |
| - iv |
21 |
| - ); |
22 |
| - const part = decipher.update(content).toString("utf8"); |
| 35 | + decipher = crypto.createDecipheriv( |
| 36 | + algorithm, |
| 37 | + key, |
| 38 | + data.iv |
| 39 | + ); |
| 40 | + } else { |
| 41 | + data = {iv: Buffer.alloc(0), content: plainInput}; |
| 42 | + decipher = crypto.createDecipher( |
| 43 | + algorithm, |
| 44 | + key |
| 45 | + ); |
| 46 | + } |
| 47 | + const part = decipher.update(data.content).toString("utf8"); |
23 | 48 | return part + decipher.final("utf8");
|
24 | 49 | };
|
0 commit comments