2020-05-03 14:46:05 -04:00
|
|
|
import * as openpgp from 'openpgp';
|
2020-05-05 14:01:45 -04:00
|
|
|
import addressparser from 'addressparser';
|
2020-05-03 14:46:05 -04:00
|
|
|
|
|
|
|
export interface PrivateKey {
|
|
|
|
fingerprint: string;
|
|
|
|
keyID: string;
|
2020-05-05 14:01:45 -04:00
|
|
|
name: string;
|
|
|
|
email: string;
|
2020-05-03 14:46:05 -04:00
|
|
|
creationTime: Date;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface KeyPair {
|
|
|
|
publicKey: string;
|
|
|
|
privateKey: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const readPrivateKey = async (armoredText: string): Promise<PrivateKey> => {
|
|
|
|
const {
|
|
|
|
keys: [privateKey],
|
|
|
|
err: err
|
|
|
|
} = await openpgp.key.readArmored(armoredText);
|
|
|
|
if (err?.length) {
|
|
|
|
throw err[0];
|
|
|
|
}
|
|
|
|
|
2020-05-05 14:01:45 -04:00
|
|
|
const address = await privateKey.getPrimaryUser().then(primaryUser => {
|
|
|
|
return addressparser(primaryUser.user.userId.userid)[0];
|
|
|
|
});
|
|
|
|
|
2020-05-03 14:46:05 -04:00
|
|
|
return {
|
|
|
|
fingerprint: privateKey.getFingerprint().toUpperCase(),
|
|
|
|
keyID: await privateKey.getEncryptionKey().then(encKey => {
|
|
|
|
// @ts-ignore
|
|
|
|
return encKey?.getKeyId().toHex().toUpperCase();
|
|
|
|
}),
|
2020-05-05 14:01:45 -04:00
|
|
|
name: address.name,
|
|
|
|
email: address.address,
|
2020-05-03 14:46:05 -04:00
|
|
|
creationTime: privateKey.getCreationTime()
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export const generateKeyPair = async (
|
|
|
|
name: string,
|
|
|
|
email: string,
|
|
|
|
passphrase: string,
|
|
|
|
numBits: number = 4096
|
|
|
|
): Promise<KeyPair> => {
|
|
|
|
const keyPair = await openpgp.generateKey({
|
|
|
|
userIds: [{name: name, email: email}],
|
|
|
|
numBits,
|
|
|
|
passphrase
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
publicKey: keyPair.publicKeyArmored.replace(/\r\n/g, '\n').trim(),
|
|
|
|
privateKey: keyPair.privateKeyArmored.replace(/\r\n/g, '\n').trim()
|
|
|
|
};
|
|
|
|
};
|