File: keyring.go

package info (click to toggle)
golang-github-protonmail-gopenpgp-v3 3.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,028 kB
  • sloc: sh: 87; makefile: 2
file content (342 lines) | stat: -rw-r--r-- 9,306 bytes parent folder | download | duplicates (2)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package crypto

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/ProtonMail/go-crypto/openpgp/packet"
	openpgp "github.com/ProtonMail/go-crypto/openpgp/v2"
)

// KeyRing contains multiple private and public keys.
type KeyRing struct {
	// PGP entities in this keyring.
	entities openpgp.EntityList

	// FirstKeyID as obtained from API to match salt
	FirstKeyID string
}

// Identity contains the name and the email of a key holder.
type Identity struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

// --- New keyrings

// NewKeyRing creates a new KeyRing, empty if key is nil.
func NewKeyRing(key *Key) (*KeyRing, error) {
	keyRing := &KeyRing{}
	var err error
	if key != nil {
		err = keyRing.AddKey(key)
	}
	return keyRing, err
}

// AddKey adds the given key to the keyring.
func (keyRing *KeyRing) AddKey(key *Key) error {
	if key.IsPrivate() {
		unlocked, err := key.IsUnlocked()
		if err != nil || !unlocked {
			return errors.New("gopenpgp: unable to add locked key to a keyring")
		}
	}

	keyRing.appendKey(key)
	return nil
}

// NewKeyRingFromBinary creates a new keyring with all the keys contained in the unarmored binary data.
// Note that it accepts only unlocked or public keys, as KeyRing cannot contain locked keys.
func NewKeyRingFromBinary(binKeys []byte) (*KeyRing, error) {
	entities, err := openpgp.ReadKeyRing(bytes.NewReader(binKeys))
	if err != nil {
		return nil, fmt.Errorf("gopenpgp: error in reading keyring: %w", err)
	}

	keyring := &KeyRing{}
	for _, entity := range entities {
		key, err := NewKeyFromEntity(entity)
		if err != nil {
			return nil, fmt.Errorf("gopenpgp: error in reading keyring: %w", err)
		}

		if err = keyring.AddKey(key); err != nil {
			return nil, fmt.Errorf("gopenpgp: error in reading keyring: %w", err)
		}
	}

	return keyring, nil
}

// --- Extract keys from keyring

// GetKeys returns openpgp keys contained in this KeyRing.
// Not supported on go mobile clients.
func (keyRing *KeyRing) GetKeys() []*Key {
	keys := make([]*Key, keyRing.CountEntities())
	for i, entity := range keyRing.entities {
		keys[i] = &Key{entity}
	}
	return keys
}

// GetKey returns the n-th openpgp key contained in this KeyRing.
func (keyRing *KeyRing) GetKey(n int) (*Key, error) {
	if n >= keyRing.CountEntities() {
		return nil, errors.New("gopenpgp: out of bound when fetching key")
	}
	return &Key{keyRing.entities[n]}, nil
}

func (keyRing *KeyRing) signingEntities() ([]*openpgp.Entity, error) {
	var signEntity []*openpgp.Entity
	for _, e := range keyRing.entities {
		// Entity.PrivateKey must be a signing key
		if e.PrivateKey != nil && !e.PrivateKey.Encrypted {
			signEntity = append(signEntity, e)
		} else {
			return nil, errors.New("gopenpgp: signing entity does not contain unencrypted private key")
		}
	}
	return signEntity, nil
}

// getEntities returns the internal EntityList if the key ring is not nil.
func (keyRing *KeyRing) getEntities() openpgp.EntityList {
	if keyRing == nil {
		return nil
	}
	return keyRing.entities
}

// Serialize serializes a KeyRing to binary data.
func (keyRing *KeyRing) Serialize() ([]byte, error) {
	var buffer bytes.Buffer

	for _, entity := range keyRing.entities {
		var err error
		if entity.PrivateKey == nil {
			err = entity.Serialize(&buffer)
		} else {
			err = entity.SerializePrivateWithoutSigning(&buffer, nil)
		}
		if err != nil {
			return nil, fmt.Errorf("gopenpgp: error in serializing keyring: %w", err)
		}
	}

	return buffer.Bytes(), nil
}

// --- Extract info from key

// CountEntities returns the number of entities in the keyring.
func (keyRing *KeyRing) CountEntities() int {
	if keyRing == nil {
		return 0
	}
	return len(keyRing.entities)
}

// CountDecryptionEntities returns the number of entities in the keyring.
// Takes the current time for checking the keys in unix time format.
// If the unix time is zero, time checks are ignored.
func (keyRing *KeyRing) CountDecryptionEntities(unixTime int64) int {
	var count int
	var checkTime time.Time
	if unixTime != 0 {
		checkTime = time.Unix(unixTime, 0)
	}
	for _, entity := range keyRing.entities {
		decryptionKeys := entity.DecryptionKeys(0, checkTime, &packet.Config{})
		count += len(decryptionKeys)
	}
	return count
}

// GetIdentities returns the list of identities associated with this key ring.
// Not supported on go-mobile clients use keyRing.GetIdentitiesJson() instead.
func (keyRing *KeyRing) GetIdentities() []*Identity {
	var identities []*Identity
	for _, e := range keyRing.entities {
		for _, id := range e.Identities {
			identities = append(identities, &Identity{
				Name:  id.UserId.Name,
				Email: id.UserId.Email,
			})
		}
	}
	return identities
}

// GetIdentitiesJson returns the list of identities associated with this key ring encoded as json.
// Returns nil if an encoding error occurs.
// Helper function for go-mobile clients.
func (keyRing *KeyRing) GetIdentitiesJson() []byte {
	identitiesJson, err := json.Marshal(keyRing.GetIdentities())
	if err != nil {
		return nil
	}
	return identitiesJson
}

// CanVerify returns true if any of the keys in the keyring can be used for verification.
func (keyRing *KeyRing) CanVerify(unixTime int64) bool {
	keys := keyRing.GetKeys()
	for _, key := range keys {
		if key.CanVerify(unixTime) {
			return true
		}
	}
	return false
}

// CanEncrypt returns true if any of the keys in the keyring can be used for encryption.
func (keyRing *KeyRing) CanEncrypt(unixTime int64) bool {
	keys := keyRing.GetKeys()
	for _, key := range keys {
		if key.CanEncrypt(unixTime) {
			return true
		}
	}
	return false
}

// GetKeyIDs returns array of IDs of keys in this KeyRing.
// Not supported on go-mobile clients.
func (keyRing *KeyRing) GetKeyIDs() []uint64 {
	var res = make([]uint64, len(keyRing.entities))
	for id, e := range keyRing.entities {
		res[id] = e.PrimaryKey.KeyId
	}
	return res
}

// GetHexKeyIDsJson returns an IDs of keys in this KeyRing as a json array.
// Key ids are encoded as hexadecimal and nil is returned if an error occurs.
// Helper function for go-mobile clients.
func (keyRing *KeyRing) GetHexKeyIDsJson() []byte {
	var res = make([]string, len(keyRing.entities))
	for id, e := range keyRing.entities {
		res[id] = keyIDToHex(e.PrimaryKey.KeyId)
	}
	keyIdsJson, err := json.Marshal(res)
	if err != nil {
		return nil
	}
	return keyIdsJson
}

// --- Filter keyrings

// FilterExpiredKeys takes a given KeyRing list and it returns only those
// KeyRings which contain at least, one unexpired Key. It returns only unexpired
// parts of these KeyRings.
func FilterExpiredKeys(contactKeys []*KeyRing) (filteredKeys []*KeyRing, err error) {
	now := time.Now()
	hasExpiredEntity := false
	filteredKeys = make([]*KeyRing, 0)

	for _, contactKeyRing := range contactKeys {
		keyRingHasUnexpiredEntity := false
		keyRingHasTotallyExpiredEntity := false
		for _, entity := range contactKeyRing.entities {
			hasExpired := false
			hasUnexpired := false
			for _, subkey := range entity.Subkeys {
				latestValid, err := subkey.LatestValidBindingSignature(now, &packet.Config{})
				if err != nil {
					hasExpired = true
				}
				if subkey.PublicKey.KeyExpired(latestValid, now) {
					hasExpired = true
				} else {
					hasUnexpired = true
				}
			}
			if hasExpired && !hasUnexpired {
				keyRingHasTotallyExpiredEntity = true
			} else if hasUnexpired {
				keyRingHasUnexpiredEntity = true
			}
		}
		if keyRingHasUnexpiredEntity {
			keyRingCopy, err := contactKeyRing.Copy()
			if err != nil {
				return nil, err
			}

			filteredKeys = append(filteredKeys, keyRingCopy)
		} else if keyRingHasTotallyExpiredEntity {
			hasExpiredEntity = true
		}
	}

	if len(filteredKeys) == 0 && hasExpiredEntity {
		return filteredKeys, errors.New("gopenpgp: all contacts keys are expired")
	}

	return filteredKeys, nil
}

// FirstKey returns a KeyRing with only the first key of the original one.
func (keyRing *KeyRing) FirstKey() (*KeyRing, error) {
	if len(keyRing.entities) == 0 {
		return nil, errors.New("gopenpgp: No key available in this keyring")
	}
	newKeyRing := &KeyRing{}
	newKeyRing.entities = keyRing.entities[:1]

	return newKeyRing.Copy()
}

// Copy creates a deep copy of the keyring.
func (keyRing *KeyRing) Copy() (*KeyRing, error) {
	newKeyRing := &KeyRing{}

	entities := make([]*openpgp.Entity, len(keyRing.entities))
	for id, entity := range keyRing.entities {
		var buffer bytes.Buffer
		var err error

		if entity.PrivateKey == nil {
			err = entity.Serialize(&buffer)
		} else {
			err = entity.SerializePrivateWithoutSigning(&buffer, nil)
		}

		if err != nil {
			return nil, fmt.Errorf("gopenpgp: unable to copy key: error in serializing entity: %w", err)
		}

		bt := buffer.Bytes()
		entities[id], err = openpgp.ReadEntity(packet.NewReader(bytes.NewReader(bt)))

		if err != nil {
			return nil, fmt.Errorf("gopenpgp: unable to copy key: error in reading entity: %w", err)
		}
	}
	newKeyRing.entities = entities
	newKeyRing.FirstKeyID = keyRing.FirstKeyID

	return newKeyRing, nil
}

func (keyRing *KeyRing) ClearPrivateParams() {
	for _, key := range keyRing.GetKeys() {
		key.ClearPrivateParams()
	}
}

// INTERNAL FUNCTIONS

// appendKey appends a key to the keyring.
func (keyRing *KeyRing) appendKey(key *Key) {
	keyRing.entities = append(keyRing.entities, key.entity)
}