Skip to content

Commit 60c14da

Browse files
author
Simon Hofmann
committed
(#11) Updated encrypt method to work with different algorithms
1 parent 33a7382 commit 60c14da

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

lib/encrypt.function.spec.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {Algorithm} from "./algorithm.enum";
12
import {encrypt} from "./encrypt.function";
23

34
describe("secret", () => {
@@ -9,6 +10,6 @@ describe("secret", () => {
910
// WHEN
1011

1112
// THEN
12-
await expect(() => encrypt(input, key)).not.toThrow();
13+
await expect(() => encrypt(input, key, Algorithm.AES128CBC)).not.toThrow();
1314
});
1415
});

lib/encrypt.function.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,27 @@
11
import * as crypto from "crypto";
2+
import {Algorithm} from "./algorithm.enum";
23
import {base64EncodedBufferFromString} from "./buffer.function";
3-
import {getAlgorithm} from "./get-algorithm.function";
4+
import {getCipherSpec} from "./get-cipher-spec.function";
45
import {generateRandom} from "./random.function";
56

6-
export const encrypt = async (plainText: string, keyBase64: string): Promise<string> => {
7-
const cipherSpec = getAlgorithm(keyBase64);
7+
export const encrypt = async (
8+
plainText: string,
9+
keyBase64: string,
10+
algorithm: Algorithm,
11+
useIV: boolean = true): Promise<string> => {
12+
const cipherSpec = getCipherSpec(algorithm);
813
const key = base64EncodedBufferFromString(keyBase64);
9-
const iv = await generateRandom({
10-
byteLength: cipherSpec.blockSize,
11-
});
1214

13-
const cipher = crypto.createCipheriv(cipherSpec.cipher, key, iv);
14-
const part = cipher.update(plainText);
15-
return Buffer.concat([iv, part, cipher.final()]).toString("base64");
15+
if (useIV) {
16+
const iv = await generateRandom({
17+
byteLength: cipherSpec.blockSize,
18+
});
19+
const cipher = crypto.createCipheriv(algorithm, key, iv);
20+
const part = cipher.update(plainText);
21+
return Buffer.concat([iv, part, cipher.final()]).toString("base64");
22+
} else {
23+
const cipher = crypto.createCipher(algorithm, key);
24+
const part = cipher.update(plainText);
25+
return Buffer.concat([part, cipher.final()]).toString("base64");
26+
}
1627
};

0 commit comments

Comments
 (0)