-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrsa.js
36 lines (34 loc) · 915 Bytes
/
rsa.js
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
import * as crypto from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { cwd } from 'node:process';
import { secretKey } from './env.js';
/**
* Get private key contents.
* @param {string} type Key type.
* @return {Promise<string | undefined>}
*/
export const getKey = async (type) => {
try {
return await readFile(resolve(cwd(), 'keys', type.concat('.pem')), {
'encoding': 'utf8',
});
} catch {
return undefined;
}
};
/**
* Convert key contents to crypto.KeyObject
* @param {string} type Key type.
* @param {string} keyStr Key contents.
* @return {crypto.KeyObject | undefined}
*/
export const toKeyObject = (type, keyStr) => {
if (type === 'private')
return crypto.createPrivateKey({
'key': keyStr,
'passphrase': secretKey,
});
else if (type === 'public') return crypto.createPublicKey(keyStr);
else return undefined;
};