1 import type { KeyReference, PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
2 import { CryptoProxy } from '@proton/crypto';
3 import { computeKeyPassword, generateKeySalt } from '@proton/srp';
5 import { extractEmailFromUserID } from '../helpers/email';
6 import type { Key, KeyPair, KeySalt as tsKeySalt } from '../interfaces';
8 export const generateKeySaltAndPassphrase = async (password: string) => {
9 const salt = generateKeySalt();
12 passphrase: await computeKeyPassword(password, salt),
17 * Given a list of keys and joining key salts, get the primary key and the corresponding key salt.
18 * @param Keys - Keys as received from the API
19 * @param KeySalts - KeySalts as received from the API
21 export const getPrimaryKeyWithSalt = (Keys: Key[] = [], KeySalts: tsKeySalt[] = []) => {
22 const [{ ID, PrivateKey } = { ID: '', PrivateKey: '' }] = Keys;
23 const { KeySalt } = KeySalts.find(({ ID: keySaltID }) => ID === keySaltID) || {};
25 // Not verifying that KeySalt exists because of old auth versions.
32 export const splitKeys = (keys: Partial<KeyPair>[] = []) => {
33 return keys.reduce<{ privateKeys: PrivateKeyReference[]; publicKeys: PublicKeyReference[] }>(
34 (acc, { privateKey, publicKey }) => {
35 if (!privateKey || !publicKey) {
38 acc.publicKeys.push(publicKey);
39 acc.privateKeys.push(privateKey);
42 { publicKeys: [], privateKeys: [] }
46 export const decryptPrivateKeyWithSalt = async ({
55 const keyPassword = keySalt ? await computeKeyPassword(password, keySalt) : password;
56 return CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: keyPassword });
59 export const getEmailFromKey = (key: KeyReference) => {
60 const [userID] = key.getUserIDs();
61 return extractEmailFromUserID(userID);