Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / shared / lib / keys / keypacket.ts
blob427fb2d714d1a33f03adbe39b42a74407a54036b
1 import type { PrivateKeyReference, PublicKeyReference, SessionKey } from '@proton/crypto';
2 import { CryptoProxy } from '@proton/crypto';
3 import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
5 export const decryptKeyPacket = async ({
6     armoredMessage,
7     decryptionKeys,
8 }: {
9     armoredMessage?: string;
10     decryptionKeys: PrivateKeyReference[];
11 }) => {
12     const sessionKey = await CryptoProxy.decryptSessionKey({
13         armoredMessage,
14         decryptionKeys,
15     });
16     if (!sessionKey) {
17         throw new Error('Missing session key');
18     }
19     const message = await CryptoProxy.decryptMessage({
20         armoredMessage,
21         sessionKeys: sessionKey,
22         format: 'binary',
23     });
24     return { message, sessionKey };
27 export const encryptAndSignKeyPacket = async ({
28     binaryData,
29     sessionKey,
30     encryptionKey,
31     signingKey,
32     context,
33 }: {
34     sessionKey: SessionKey;
35     binaryData: Uint8Array;
36     encryptionKey: PublicKeyReference;
37     signingKey: PrivateKeyReference;
38     context?: Parameters<typeof CryptoProxy.signMessage<any>>[0]['context'];
39 }) => {
40     const result = await CryptoProxy.encryptSessionKey({
41         ...sessionKey,
42         encryptionKeys: [encryptionKey],
43         format: 'binary',
44     });
46     const signature = await CryptoProxy.signMessage({
47         binaryData,
48         signingKeys: [signingKey],
49         detached: true,
50         context,
51     });
53     return {
54         keyPacket: uint8ArrayToBase64String(result),
55         signature,
56     };