generated from actions/typescript-action
-
Notifications
You must be signed in to change notification settings - Fork 3
/
openpgp.ts
76 lines (65 loc) · 1.69 KB
/
openpgp.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
import * as openpgp from 'openpgp'
import {EmailAddress} from '../email-address'
export interface PrivateKey {
fingerprint: string
keyID: string
name: string
email: string
creationTime: Date
}
export interface KeyPair {
publicKey: string
privateKey: string
}
export interface Address {
name: string
address: string
}
export const readPrivateKey = async (key: string): Promise<PrivateKey> => {
const privateKey = await openpgp.readKey({
armoredKey: (await isArmored(key))
? key
: Buffer.from(key, 'base64').toString()
})
const primaryUser = await privateKey.getPrimaryUser()
const address = addressParser(primaryUser.user.userID?.userID)
return {
fingerprint: privateKey.getFingerprint().toUpperCase(),
keyID: privateKey.getKeyID().toHex().toUpperCase(),
name: address.name,
email: address.address,
creationTime: privateKey.getCreationTime()
}
}
export const generateKeyPair = async (
name: string,
email: string,
passphrase: string,
type?: 'ecc' | 'rsa'
): Promise<KeyPair> => {
const keyPair = await openpgp.generateKey({
userIDs: [{name, email}],
passphrase,
type
})
return {
publicKey: keyPair.publicKey.replace(/\r\n/g, '\n').trim(),
privateKey: keyPair.privateKey.replace(/\r\n/g, '\n').trim()
}
}
export const isArmored = async (text: string): Promise<boolean> => {
return text.trimStart().startsWith('---')
}
function addressParser(address: string | undefined): Address {
if (address === undefined) {
return {
name: '',
address: ''
}
}
const emailAddress = new EmailAddress(address)
return {
name: emailAddress.getDisplayName(),
address: emailAddress.getEmail()
}
}