-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys.encryption-utils.ts
347 lines (309 loc) · 9.87 KB
/
keys.encryption-utils.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import {IKeyValue, stringify} from '@pashoo2/serialization-utils';
import {typedArrayToString} from '@pashoo2/typed-array-utils';
import {
CRYPTO_UTIL_GENERATE_KEYPAIR_OPTIONS,
CRYPTO_UTIL_KEYPAIR_USAGES,
CRYPTO_UTIL_PUBLIC_KEY_USAGE,
CRYPTO_UTIL_PRIVATE_KEY_USAGE,
CRYPTO_UTIL_KEYPAIR_EXPORT_FORMAT,
CRYPTO_UTIL_KEY_DESC,
CRYPTO_UTIL_KEYS_EXTRACTABLE,
CRYPTO_UTIL_KEYPAIR_PUBLIC_KEY_NAME,
CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME,
} from './crypto-utils.const';
import {
TCryptoUtilKeyExportFormatType,
TCryptoUtilKeypairExportFormatType,
TCryptoUtilKeypairImportFormatType,
TCryptoUtilEncryptKeyTypes,
} from './crypto-utils.types';
import {generateSalt} from './salt-utils';
import {CRYPTO_UTIL_KEYPAIR_SALT_KEY_NAME} from './crypto-utils.const';
import {encryptDataWithPassword} from '../password-utils/encrypt.password-utils';
import {TCryptoUtilKeypairPreImportFormatType} from './crypto-utils.types';
import {decryptDataByPassword} from '../password-utils/decrypt.password-utils';
import {
isCryptoKeyPair,
isCryptoKey,
} from '../encryption-keys-utils/encryption-keys-utils';
import {isTypedArray} from '@pashoo2/typed-array-utils';
import {cryptoModuleDataSign} from '../init';
export const isCryptoKeyPairImported = (
key: any,
checkPrivateKey = true
): key is TCryptoUtilKeypairExportFormatType => {
return (
typeof key === 'object' &&
!!key[CRYPTO_UTIL_KEYPAIR_PUBLIC_KEY_NAME] &&
(!checkPrivateKey || !!key[CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME])
);
};
export const generateKeyPair = (): PromiseLike<CryptoKeyPair> =>
cryptoModuleDataSign.generateKey(
CRYPTO_UTIL_GENERATE_KEYPAIR_OPTIONS,
CRYPTO_UTIL_KEYS_EXTRACTABLE,
CRYPTO_UTIL_KEYPAIR_USAGES
);
export const exportKey = (
key: CryptoKey
): PromiseLike<TCryptoUtilKeyExportFormatType | Error> => {
try {
return cryptoModuleDataSign.exportKey(
CRYPTO_UTIL_KEYPAIR_EXPORT_FORMAT,
key
);
} catch (err) {
console.error(err);
return err;
}
};
export const exportKeyAsString = async (
key: CryptoKey
): Promise<Error | string> => {
return stringify((await exportKey(key)) as IKeyValue);
};
export const exportPublicKey = async (keyPair: CryptoKeyPair) => {
return await exportKey(keyPair.publicKey);
};
export const exportPublicKeyAsString = async (keyPair: CryptoKeyPair) => {
const publicKey = await exportPublicKey(keyPair);
if (publicKey instanceof Error) {
return publicKey;
}
return stringify(publicKey as IKeyValue);
};
export const exportKeyPair = async (
keyPair: CryptoKeyPair,
password?: string
): Promise<TCryptoUtilKeypairExportFormatType | Error> => {
try {
if (isCryptoKeyPair(keyPair, !!password)) {
// do it in parallel
const [privateKey, publicKey] = await Promise.all([
password || keyPair.privateKey
? exportKey(keyPair.privateKey)
: Promise.resolve(undefined),
exportKey(keyPair.publicKey),
]).catch(err => [err, err]);
if (privateKey instanceof Error) {
return privateKey;
}
if (publicKey instanceof Error) {
return publicKey;
}
const result: TCryptoUtilKeypairExportFormatType = {
[CRYPTO_UTIL_KEYPAIR_PUBLIC_KEY_NAME]: publicKey,
[CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME]: privateKey,
};
if (password) {
const salt = generateSalt();
if (salt instanceof Error) {
return new Error('Failed to generate a unique salt value');
}
const encryptedPrivateKey = await encryptDataWithPassword(
password,
salt,
privateKey
);
if (encryptedPrivateKey instanceof Error) {
return new Error(
'Failed to encrypt private key with password provided'
);
}
const saltStringified = typedArrayToString(salt);
const decryptedPrivateKey = await decryptDataByPassword(
password,
saltStringified,
encryptedPrivateKey
);
if (decryptedPrivateKey instanceof Error) {
return new Error('Failed to decrypt private key for data encryption');
}
result[CRYPTO_UTIL_KEYPAIR_SALT_KEY_NAME] = saltStringified;
result[CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME] = encryptedPrivateKey;
}
return result;
}
return new Error('Argument given must be a CryptoKeyPair');
} catch (err) {
return err;
}
};
export const exportKeyPairAsString = async (
keyPair: CryptoKeyPair,
password?: string
): Promise<string | Error> => {
const exportedKeyPair = await exportKeyPair(keyPair, password);
if (exportedKeyPair instanceof Error) {
return exportedKeyPair;
}
if (isTypedArray(exportedKeyPair)) {
return typedArrayToString(exportedKeyPair);
}
try {
return stringify(exportedKeyPair as JsonWebKey as IKeyValue);
} catch (err) {
return err;
}
};
export const importKey = (
key: object,
isPublic = true
): PromiseLike<CryptoKey> => {
return cryptoModuleDataSign.importKey(
CRYPTO_UTIL_KEYPAIR_EXPORT_FORMAT,
key,
CRYPTO_UTIL_KEY_DESC,
CRYPTO_UTIL_KEYS_EXTRACTABLE,
[isPublic ? CRYPTO_UTIL_PUBLIC_KEY_USAGE : CRYPTO_UTIL_PRIVATE_KEY_USAGE]
);
};
export const importPublicKey = (key: object): PromiseLike<CryptoKey> =>
importKey(key, true);
export const importPrivateKey = (key: object): PromiseLike<CryptoKey> =>
importKey(key, false);
export const importKeyPair = async (
keyPair: TCryptoUtilKeypairPreImportFormatType,
checkPrivateKey = true
): Promise<TCryptoUtilKeypairImportFormatType | Error> => {
try {
if (isCryptoKeyPairImported(keyPair, checkPrivateKey)) {
const importResult = await Promise.all([
(async () => {
try {
return await importPublicKey(
keyPair[CRYPTO_UTIL_KEYPAIR_PUBLIC_KEY_NAME]
);
} catch (err) {
return err;
}
})(),
(async () => {
try {
if (
checkPrivateKey ||
keyPair[CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME]
) {
return await importPrivateKey(
keyPair[CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME]
);
}
} catch (err) {
return err;
}
})(),
]);
const publicKey = importResult[0];
let privateKey = importResult[1];
if (publicKey instanceof Error) {
return publicKey;
}
if (privateKey instanceof Error) {
if (checkPrivateKey) {
return privateKey;
}
privateKey = undefined;
}
return {
[CRYPTO_UTIL_KEYPAIR_PUBLIC_KEY_NAME]: publicKey,
[CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME]: privateKey,
};
}
return new Error('The argument must be an instance of CryptoKeyPair');
} catch (err) {
return err;
}
};
export const importKeyPairFromString = async (
keyPairString: string,
password?: string
): Promise<TCryptoUtilKeypairImportFormatType | Error> => {
try {
if (typeof keyPairString === 'string') {
const keyPairObject = JSON.parse(keyPairString);
if (password && keyPairObject[CRYPTO_UTIL_KEYPAIR_SALT_KEY_NAME]) {
if (
typeof keyPairObject[CRYPTO_UTIL_KEYPAIR_SALT_KEY_NAME] !== 'string'
) {
return new Error('A salt value must be a string');
}
const decryptedPrivateKey = await decryptDataByPassword(
password,
keyPairObject[CRYPTO_UTIL_KEYPAIR_SALT_KEY_NAME],
keyPairObject[CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME]
);
if (decryptedPrivateKey instanceof Error) {
console.error('Failed to decrypt the data encryption private key');
return decryptedPrivateKey;
}
try {
keyPairObject[CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME] =
JSON.parse(decryptedPrivateKey);
} catch (err) {
console.error(err);
return new Error(
'Failed to parse dataencryption Private key from the string decrypted'
);
}
}
return await importKeyPair(keyPairObject, !!password);
}
return new Error('A key pair must be a string');
} catch (err) {
return err;
}
};
export const importKeyFromString = (
keyString: string,
isPublic = true
): PromiseLike<CryptoKey> | Error => {
try {
return importKey(JSON.parse(keyString), isPublic);
} catch (err) {
return err;
}
};
export const importPublicKeyFromString = (
key: string
): PromiseLike<CryptoKey> | Error => importKeyFromString(key, true);
export const importPrivateKeyFromString = (
key: string
): PromiseLike<CryptoKey> | Error => importKeyFromString(key, false);
export const checkIfStringIsKeyPair = (keyString: string): boolean => {
return (
keyString.includes(CRYPTO_UTIL_KEYPAIR_PRIVATE_KEY_NAME) &&
keyString.includes(CRYPTO_UTIL_KEYPAIR_PUBLIC_KEY_NAME)
);
};
const KEY_NOT_FOUND_ERROR_MESSAGE = 'A key of the required type was not found';
export const getKeyOfType = async (
key: TCryptoUtilEncryptKeyTypes,
type: KeyType
): Promise<CryptoKey | Error> => {
if (typeof key === 'string') {
if (checkIfStringIsKeyPair(key)) {
const keyPair = await importKeyPairFromString(key);
if (keyPair instanceof Error) {
return keyPair;
}
return getKeyOfType(keyPair, type);
} else {
const keyFromString = await importKeyFromString(key, type === 'public');
if (keyFromString instanceof Error) {
return keyFromString;
}
return getKeyOfType(keyFromString, type);
}
}
if (isCryptoKey(key)) {
return key.type === type ? key : new Error(KEY_NOT_FOUND_ERROR_MESSAGE);
}
if (typeof key === 'object') {
const keys = Object.values(key);
const keyResulted = keys.find(
(k: CryptoKey) => k && k.type && k.type === type
);
return keyResulted || new Error(KEY_NOT_FOUND_ERROR_MESSAGE);
}
return new Error('There is an unsupported type of the key given');
};