|
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 {getCipherSpec} from "./get-cipher-spec.function"; |
4 | 5 | import {generateRandom} from "./random.function";
|
5 | 6 |
|
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); |
8 | 13 | const key = base64EncodedBufferFromString(keyBase64);
|
9 |
| - const iv = await generateRandom({ |
10 |
| - byteLength: cipherSpec.blockSize, |
11 |
| - }); |
12 | 14 |
|
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 | + } |
16 | 27 | };
|
0 commit comments