2020-05-03 20:46:05 +02:00
|
|
|
import * as openpgp from 'openpgp';
|
2020-05-05 20:01:45 +02:00
|
|
|
import addressparser from 'addressparser';
|
2020-05-03 20:46:05 +02:00
|
|
|
|
|
|
|
export interface PrivateKey {
|
|
|
|
fingerprint: string;
|
|
|
|
keyID: string;
|
2020-05-05 20:01:45 +02:00
|
|
|
name: string;
|
|
|
|
email: string;
|
2020-05-03 20:46:05 +02:00
|
|
|
creationTime: Date;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface KeyPair {
|
|
|
|
publicKey: string;
|
|
|
|
privateKey: string;
|
|
|
|
}
|
|
|
|
|
2020-05-18 17:31:00 +02:00
|
|
|
export const readPrivateKey = async (key: string): Promise<PrivateKey> => {
|
2021-09-05 01:00:24 +02:00
|
|
|
const privateKey = await openpgp.readKey({
|
|
|
|
armoredKey: (await isArmored(key)) ? key : Buffer.from(key, 'base64').toString()
|
|
|
|
});
|
2020-05-03 20:46:05 +02:00
|
|
|
|
2020-05-05 20:01:45 +02:00
|
|
|
const address = await privateKey.getPrimaryUser().then(primaryUser => {
|
2021-09-05 01:00:24 +02:00
|
|
|
return addressparser(primaryUser.user.userID?.userID)[0];
|
2020-05-05 20:01:45 +02:00
|
|
|
});
|
|
|
|
|
2020-05-03 20:46:05 +02:00
|
|
|
return {
|
|
|
|
fingerprint: privateKey.getFingerprint().toUpperCase(),
|
2021-10-15 13:40:04 +02:00
|
|
|
keyID: privateKey.getKeyID().toHex().toUpperCase(),
|
2020-05-05 20:01:45 +02:00
|
|
|
name: address.name,
|
|
|
|
email: address.address,
|
2020-05-03 20:46:05 +02:00
|
|
|
creationTime: privateKey.getCreationTime()
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2021-09-05 01:00:24 +02:00
|
|
|
export const generateKeyPair = async (name: string, email: string, passphrase: string, type?: 'ecc' | 'rsa'): Promise<KeyPair> => {
|
2020-05-03 20:46:05 +02:00
|
|
|
const keyPair = await openpgp.generateKey({
|
2021-09-05 01:00:24 +02:00
|
|
|
userIDs: [{name: name, email: email}],
|
|
|
|
passphrase: passphrase,
|
|
|
|
type: type
|
2020-05-03 20:46:05 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
2021-09-05 01:00:24 +02:00
|
|
|
publicKey: keyPair.publicKey.replace(/\r\n/g, '\n').trim(),
|
|
|
|
privateKey: keyPair.privateKey.replace(/\r\n/g, '\n').trim()
|
2020-05-03 20:46:05 +02:00
|
|
|
};
|
|
|
|
};
|
2020-05-13 14:10:12 +02:00
|
|
|
|
2020-05-18 17:31:00 +02:00
|
|
|
export const isArmored = async (text: string): Promise<boolean> => {
|
|
|
|
return text.trimLeft().startsWith('---');
|
|
|
|
};
|