gpg/src/openpgp.ts

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-05-03 14:46:05 -04:00
import * as openpgp from 'openpgp';
import addressparser from 'addressparser';
2020-05-03 14:46:05 -04:00
export interface PrivateKey {
fingerprint: string;
keyID: string;
name: string;
email: string;
2020-05-03 14:46:05 -04:00
creationTime: Date;
}
export interface KeyPair {
publicKey: string;
privateKey: string;
}
2020-05-18 11:31:00 -04:00
export const readPrivateKey = async (key: string): Promise<PrivateKey> => {
2020-05-03 14:46:05 -04:00
const {
keys: [privateKey],
err: err
2020-05-18 11:31:00 -04:00
} = await openpgp.key.readArmored((await isArmored(key)) ? key : Buffer.from(key, 'base64').toString());
2020-05-03 14:46:05 -04:00
if (err?.length) {
throw err[0];
}
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();
}),
name: address.name,
email: address.address,
2020-05-03 14:46:05 -04:00
creationTime: privateKey.getCreationTime()
};
};
2020-05-06 12:00:13 -04:00
export const generateKeyPair = async (name: string, email: string, passphrase: string, numBits: number = 4096): Promise<KeyPair> => {
2020-05-03 14:46:05 -04:00
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()
};
};
2020-05-18 11:31:00 -04:00
export const isArmored = async (text: string): Promise<boolean> => {
return text.trimLeft().startsWith('---');
};