-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryption.service.ts
72 lines (63 loc) · 1.91 KB
/
encryption.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import {
DecryptionResult,
EncyrptionResult,
RSAKey,
TransportedMessage,
TransportMessage,
} from './types';
import { AES } from './aes';
import { RSA } from './rsa';
import { arrayBufferToString, stringToArrayBuffer } from './util';
export class EncryptionService {
private readonly rsa = new RSA();
private readonly aes = new AES();
generateRsaKey(passphrase: string): RSAKey {
return this.rsa.generateKey(passphrase);
}
publicKeyString(key: RSAKey): string {
return this.rsa.publicKeyString(key);
}
async generateTransportMessage(
payload: string,
partnerPublicKey: string,y
): Promise<TransportMessage> {
const iv = this.aes.getIv();
const transportKey = await this.aes.generateKey();
const exportedKey = await this.aes.exportKey(transportKey);
const encPayload = await this.aes.encrypt(payload, transportKey, iv);
const { cipher }: EncyrptionResult = this.rsa.encrypt(
exportedKey,
partnerPublicKey,
);
return {
encryptedPayload: arrayBufferToString(encPayload),
transportKey: cipher,
iv: arrayBufferToString(iv),
};
}
async decryptTransportMessage(
transportedMessage: TransportedMessage,
key: RSAKey
): Promise<string> {
const { plaintext }: DecryptionResult = await this.rsa.decrypt(
transportedMessage.transportKey,
key
);
const decTransportKey = JSON.parse(plaintext);
const importedDecTransportKey = await this.aes.importKey(decTransportKey);
return await this.aes.decrypt(
transportedMessage.encryptedPayload,
importedDecTransportKey,
transportedMessage.iv
);
}
parseTransportMessage(
transportMessage: TransportMessage
): TransportedMessage {
return {
encryptedPayload: stringToArrayBuffer(transportMessage.encryptedPayload),
transportKey: transportMessage.transportKey,
iv: stringToArrayBuffer(transportMessage.iv),
};
}
}