Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-protocol/src/encryption/encryption-engine.ts
2500 views
1
/**
2
* Copyright (c) 2020 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
import "reflect-metadata";
7
8
import * as crypto from "crypto";
9
import { injectable } from "inversify";
10
11
export interface KeyParams {
12
iv: string;
13
}
14
15
export interface EncryptedData {
16
/** utf8 encoded string */
17
data: string;
18
keyParams: KeyParams;
19
}
20
21
export const EncryptionEngine = Symbol("EncryptionEngine");
22
export interface EncryptionEngine {
23
/**
24
* @param data utf8 encoded string
25
*/
26
encrypt(data: string, key: Buffer): EncryptedData;
27
decrypt(encryptedData: EncryptedData, key: Buffer): string;
28
}
29
30
/**
31
* For starters, let's use aes-cbc-256 with:
32
* - 16 bytes/128 bits IV (the size of an aes-256-cbc block)
33
* - no salt, as we pass in a real key (no salting needed to turn a password into a key)
34
* The implementation closely follows the exampes in https://nodejs.org/api/crypto.html.
35
*/
36
@injectable()
37
export class EncryptionEngineImpl {
38
readonly algorithm = "aes-256-cbc";
39
readonly enc = "base64";
40
41
encrypt(data: string, key: Buffer): EncryptedData {
42
const iv = crypto.randomBytes(16);
43
const cipher = crypto.createCipheriv(this.algorithm, key, iv);
44
const encrypted = cipher.update(Buffer.from(data, "utf8"));
45
const finalEncrypted = Buffer.concat([encrypted, cipher.final()]);
46
return {
47
data: finalEncrypted.toString(this.enc),
48
keyParams: {
49
iv: iv.toString(this.enc),
50
},
51
};
52
}
53
54
decrypt(encryptedData: EncryptedData, key: Buffer): string {
55
const decipher = crypto.createDecipheriv(
56
this.algorithm,
57
key,
58
Buffer.from(encryptedData.keyParams.iv, this.enc),
59
);
60
const decrypted = decipher.update(Buffer.from(encryptedData.data, this.enc));
61
const finalDecrypted = Buffer.concat([decrypted, decipher.final()]);
62
return finalDecrypted.toString("utf8");
63
}
64
}
65
66