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-service.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
7
import { injectable, inject } from "inversify";
8
9
import { EncryptedData, EncryptionEngine } from "./encryption-engine";
10
import { KeyProvider, KeyMetadata } from "./key-provider";
11
12
export interface Encrypted<_T> extends EncryptedData {
13
keyMetadata: KeyMetadata;
14
}
15
16
export const EncryptionService = Symbol("EncryptionService");
17
export interface EncryptionService {
18
encrypt<T>(data: T): Encrypted<T>;
19
decrypt<T>(encrypted: Encrypted<T>): T;
20
}
21
22
@injectable()
23
export class EncryptionServiceImpl implements EncryptionService {
24
@inject(EncryptionEngine) protected readonly engine: EncryptionEngine;
25
@inject(KeyProvider) protected readonly keyProvider: KeyProvider;
26
27
encrypt<T>(data: T): Encrypted<T> {
28
const dataStr = this.serialize(data);
29
const key = this.keyProvider.getPrimaryKey();
30
31
const encryptedData = this.engine.encrypt(dataStr, key.material);
32
return {
33
...encryptedData,
34
keyMetadata: key.metadata,
35
};
36
}
37
38
decrypt<T>(encrypted: Encrypted<T>): T {
39
const key = this.keyProvider.getKeyFor(encrypted.keyMetadata);
40
const serializedData = this.engine.decrypt(encrypted, key.material);
41
return this.deserialize(serializedData);
42
}
43
44
protected serialize(data: any): string {
45
return JSON.stringify(data);
46
}
47
48
protected deserialize<T>(data: string): T {
49
return JSON.parse(data) as T;
50
}
51
}
52
53
/** HACK ahead: Some entities - namely DBTokenEntry for now - need access to an EncryptionService so we publish it here */
54
export namespace GlobalEncryptionService {
55
export let encryptionService: EncryptionService;
56
}
57
58
export function getGlobalEncryptionService() {
59
return GlobalEncryptionService.encryptionService;
60
}
61
62