Debian Codegraph @

openpgp/keys_test.go

raw
1 package openpgp
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/dsa"
7 "crypto/rand"
8 "crypto/rsa"
9 "fmt"
10 "math/big"
11 "strconv"
12 "strings"
13 "testing"
14 "time"
15
16 "github.com/ProtonMail/go-crypto/openpgp/armor"
17 "github.com/ProtonMail/go-crypto/openpgp/ecdh"
18 "github.com/ProtonMail/go-crypto/openpgp/ecdsa"
19 "github.com/ProtonMail/go-crypto/openpgp/eddsa"
20 "github.com/ProtonMail/go-crypto/openpgp/elgamal"
21 "github.com/ProtonMail/go-crypto/openpgp/errors"
22 "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
23 "github.com/ProtonMail/go-crypto/openpgp/packet"
24 "github.com/ProtonMail/go-crypto/openpgp/s2k"
25 )
26
27 var hashes = []crypto.Hash{
28 crypto.SHA1,
29 crypto.SHA224,
30 crypto.SHA256,
31 crypto.SHA384,
32 crypto.SHA512,
33 crypto.SHA3_256,
34 crypto.SHA3_512,
35 }
36
37 var ciphers = []packet.CipherFunction{
38 packet.Cipher3DES,
39 packet.CipherCAST5,
40 packet.CipherAES128,
41 packet.CipherAES192,
42 packet.CipherAES256,
43 }
44
45 var aeadModes = []packet.AEADMode{
46 packet.AEADModeOCB,
47 packet.AEADModeEAX,
48 packet.AEADModeGCM,
49 }
50
51 func TestKeyExpiry(t *testing.T) {
52 kring, err := ReadKeyRing(readerFromHex(expiringKeyHex))
53 if err != nil {
54 t.Fatal(err)
55 }
56 entity := kring[0]
57
58 const timeFormat = "2006-01-02"
59 time1, _ := time.Parse(timeFormat, "2013-07-02")
60
61 // The expiringKeyHex key is structured as:
62 //
63 // pub 1024R/5E237D8C created: 2013-07-01 expires: 2013-07-31 usage: SC
64 // sub 1024R/1ABB25A0 created: 2013-07-01 23:11:07 +0200 CEST expires: 2013-07-08 usage: E
65 // sub 1024R/96A672F5 created: 2013-07-01 23:11:23 +0200 CEST expires: 2013-07-31 usage: E
66 //
67 // So this should select the newest, non-expired encryption key.
68 key, ok := entity.EncryptionKey(time1)
69 if !ok {
70 t.Fatal("No encryption key found")
71 }
72 if id, expected := key.PublicKey.KeyIdShortString(), "CD3D39FF"; id != expected {
73 t.Errorf("Expected key %s at time %s, but got key %s", expected, time1.Format(timeFormat), id)
74 }
75
76 // Once the first encryption subkey has expired, the second should be
77 // selected.
78 time2, _ := time.Parse(timeFormat, "2013-07-09")
79 key, _ = entity.EncryptionKey(time2)
80 if id, expected := key.PublicKey.KeyIdShortString(), "CD3D39FF"; id != expected {
81 t.Errorf("Expected key %s at time %s, but got key %s", expected, time2.Format(timeFormat), id)
82 }
83
84 // Once all the keys have expired, nothing should be returned.
85 time3, _ := time.Parse(timeFormat, "2013-08-01")
86 if key, ok := entity.EncryptionKey(time3); ok {
87 t.Errorf("Expected no key at time %s, but got key %s", time3.Format(timeFormat), key.PublicKey.KeyIdShortString())
88 }
89 }
90
91 // https://tests.sequoia-pgp.org/#Certificate_expiration
92 // P _ U f
93 func TestExpiringPrimaryUIDKey(t *testing.T) {
94 // P _ U f
95 kring, err := ReadArmoredKeyRing(bytes.NewBufferString((expiringPrimaryUIDKey)))
96 if err != nil {
97 t.Fatal(err)
98 }
99 entity := kring[0]
100
101 const timeFormat string = "2006-01-02"
102 const expectedKeyID string = "015E7330"
103
104 // Before the primary UID has expired, the primary key should be returned.
105 time1, err := time.Parse(timeFormat, "2022-02-05")
106 if err != nil {
107 t.Fatal(err)
108 }
109 key, found := entity.SigningKey(time1)
110 if !found {
111 t.Errorf("Signing subkey %s not found at time %s", expectedKeyID, time1.Format(timeFormat))
112 } else if observedKeyID := key.PublicKey.KeyIdShortString(); observedKeyID != expectedKeyID {
113 t.Errorf("Expected key %s at time %s, but got key %s", expectedKeyID, time1.Format(timeFormat), observedKeyID)
114 }
115
116 // After the primary UID has expired, nothing should be returned.
117 time2, err := time.Parse(timeFormat, "2022-02-06")
118 if err != nil {
119 t.Fatal(err)
120 }
121 if key, ok := entity.SigningKey(time2); ok {
122 t.Errorf("Expected no key at time %s, but got key %s", time2.Format(timeFormat), key.PublicKey.KeyIdShortString())
123 }
124 }
125
126 func TestReturnNewestUnexpiredSigningSubkey(t *testing.T) {
127 // Make a master key.
128 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
129 if err != nil {
130 t.Fatal(err)
131 }
132
133 // First signing subkey does not expire.
134 err = entity.AddSigningSubkey(nil)
135 if err != nil {
136 t.Fatal(err)
137 }
138 // Get the first signing subkey (added after the default encryption subkey).
139 subkey1 := entity.Subkeys[1]
140
141 // Second signing subkey expires in a day.
142 err = entity.AddSigningSubkey(&packet.Config{
143 Time: func() time.Time {
144 return time.Now().Add(1 * time.Second)
145 },
146 KeyLifetimeSecs: 24 * 60 * 60,
147 })
148 if err != nil {
149 t.Fatal(err)
150 }
151 // Get the second signing subkey.
152 subkey2 := entity.Subkeys[2]
153
154 // Before second signing subkey has expired, it should be returned.
155 time1 := time.Now().Add(2 * time.Second)
156 expected := subkey2.PublicKey.KeyIdShortString()
157 subkey, found := entity.SigningKey(time1)
158 if !found {
159 t.Errorf("Signing subkey %s not found at time %s", expected, time1.Format(time.UnixDate))
160 }
161 observed := subkey.PublicKey.KeyIdShortString()
162 if observed != expected {
163 t.Errorf("Expected key %s at time %s, but got key %s", expected, time1.Format(time.UnixDate), observed)
164 }
165
166 // After the second signing subkey has expired, the first one should be returned.
167 time2 := time1.AddDate(0, 0, 2)
168 expected = subkey1.PublicKey.KeyIdShortString()
169 subkey, found = entity.SigningKey(time2)
170 if !found {
171 t.Errorf("Signing subkey %s not found at time %s", expected, time2.Format(time.UnixDate))
172 }
173 observed = subkey.PublicKey.KeyIdShortString()
174 if observed != expected {
175 t.Errorf("Expected key %s at time %s, but got key %s", expected, time2.Format(time.UnixDate), observed)
176 }
177 }
178
179 func TestSignatureExpiry(t *testing.T) {
180 // Make a master key, and attach it to a keyring.
181 var keyring EntityList
182 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
183 if err != nil {
184 t.Fatal(err)
185 }
186 keyring = append(keyring, entity)
187
188 // Make a signature that never expires.
189 var signatureWriter1 bytes.Buffer
190 const input string = "Hello, world!"
191 message := strings.NewReader(input)
192 err = ArmoredDetachSign(&signatureWriter1, entity, message, nil)
193 if err != nil {
194 t.Fatal(err)
195 }
196
197 // Make a signature that expires in a day.
198 var signatureWriter2 bytes.Buffer
199 message = strings.NewReader(input)
200 err = ArmoredDetachSign(&signatureWriter2, entity, message, &packet.Config{
201 SigLifetimeSecs: 24 * 60 * 60,
202 })
203 if err != nil {
204 t.Fatal(err)
205 }
206
207 // Make a time that is day after tomorrow.
208 futureTime := func() time.Time {
209 return time.Now().AddDate(0, 0, 2)
210 }
211
212 // Make a signature that was created in the future.
213 var signatureWriter3 bytes.Buffer
214 message = strings.NewReader(input)
215 err = ArmoredDetachSign(&signatureWriter3, entity, message, &packet.Config{
216 Time: futureTime,
217 })
218 if err != nil {
219 t.Fatal(err)
220 }
221
222 // Check that the first signature has not expired day after tomorrow.
223 message = strings.NewReader(input)
224 signatureReader1 := strings.NewReader(signatureWriter1.String())
225 _, err = CheckArmoredDetachedSignature(keyring, message, signatureReader1, &packet.Config{
226 Time: futureTime,
227 })
228 if err != nil {
229 t.Fatal(err)
230 }
231
232 // Check that the second signature has expired day after tomorrow.
233 message = strings.NewReader(input)
234 signatureReader2 := strings.NewReader(signatureWriter2.String())
235 const expectedErr string = "openpgp: signature expired"
236 _, observedErr := CheckArmoredDetachedSignature(keyring, message, signatureReader2, &packet.Config{
237 Time: futureTime,
238 })
239 if observedErr.Error() != expectedErr {
240 t.Errorf("Expected error '%s', but got error '%s'", expectedErr, observedErr)
241 }
242
243 // Check that the third signature is also considered expired even now.
244 message = strings.NewReader(input)
245 signatureReader3 := strings.NewReader(signatureWriter3.String())
246 _, observedErr = CheckArmoredDetachedSignature(keyring, message, signatureReader3, nil)
247 if observedErr.Error() != expectedErr {
248 t.Errorf("Expected error '%s', but got error '%s'", expectedErr, observedErr)
249 }
250 }
251
252 func TestMissingCrossSignature(t *testing.T) {
253 // This public key has a signing subkey, but the subkey does not
254 // contain a cross-signature.
255 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(missingCrossSignatureKey))
256 if len(keys) != 0 {
257 t.Errorf("Accepted key with missing cross signature")
258 }
259 if err == nil {
260 t.Fatal("Failed to detect error in keyring with missing cross signature")
261 }
262 structural, ok := err.(errors.StructuralError)
263 if !ok {
264 t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err)
265 }
266 const expectedMsg = "signing subkey is missing cross-signature"
267 if !strings.Contains(string(structural), expectedMsg) {
268 t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg)
269 }
270 }
271
272 func TestInvalidCrossSignature(t *testing.T) {
273 // This public key has a signing subkey, and the subkey has an
274 // embedded cross-signature. However, the cross-signature does
275 // not correctly validate over the primary and subkey.
276 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(invalidCrossSignatureKey))
277 if len(keys) != 0 {
278 t.Errorf("Accepted key with invalid cross signature")
279 }
280 if err == nil {
281 t.Fatal("Failed to detect error in keyring with an invalid cross signature")
282 }
283 structural, ok := err.(errors.StructuralError)
284 if !ok {
285 t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err)
286 }
287 const expectedMsg = "subkey signature invalid"
288 if !strings.Contains(string(structural), expectedMsg) {
289 t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg)
290 }
291 }
292
293 func TestGoodCrossSignature(t *testing.T) {
294 // This public key has a signing subkey, and the subkey has an
295 // embedded cross-signature which correctly validates over the
296 // primary and subkey.
297 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(goodCrossSignatureKey))
298 if err != nil {
299 t.Fatal(err)
300 }
301 if len(keys) != 1 {
302 t.Errorf("Failed to accept key with good cross signature, %d", len(keys))
303 }
304 if len(keys[0].Subkeys) != 1 {
305 t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
306 }
307 }
308
309 func TestRevokedUserID(t *testing.T) {
310 // This key contains 2 UIDs, one of which is revoked and has no valid self-signature:
311 // [ultimate] (1) Golang Gopher <[email protected]>
312 // [ revoked] (2) Golang Gopher <[email protected]>
313 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(revokedUserIDKey))
314 if err != nil {
315 t.Fatal(err)
316 }
317
318 if len(keys) != 1 {
319 t.Fatal("Failed to read key with a revoked user id")
320 }
321
322 identities := keys[0].Identities
323
324 if numIdentities, numExpected := len(identities), 2; numIdentities != numExpected {
325 t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
326 }
327
328 firstIdentity, found := identities["Golang Gopher <[email protected]>"]
329 if !found {
330 t.Errorf("missing first identity")
331 }
332
333 secondIdentity, found := identities["Golang Gopher <[email protected]>"]
334 if !found {
335 t.Errorf("missing second identity")
336 }
337
338 if firstIdentity.Revoked(time.Now()) {
339 t.Errorf("expected first identity not to be revoked")
340 }
341
342 if !secondIdentity.Revoked(time.Now()) {
343 t.Errorf("expected second identity to be revoked")
344 }
345
346 const timeFormat = "2006-01-02"
347 time1, _ := time.Parse(timeFormat, "2020-01-01")
348
349 if _, found := keys[0].SigningKey(time1); !found {
350 t.Errorf("Expected SigningKey to return a signing key when one User IDs is revoked")
351 }
352
353 if _, found := keys[0].EncryptionKey(time1); !found {
354 t.Errorf("Expected EncryptionKey to return an encryption key when one User IDs is revoked")
355 }
356 }
357
358 func TestFirstUserIDRevoked(t *testing.T) {
359 // Same test as above, but with the User IDs reversed:
360 // [ revoked] (1) Golang Gopher <[email protected]>
361 // [ultimate] (2) Golang Gopher <[email protected]>
362 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithFirstUserIDRevoked))
363 if err != nil {
364 t.Fatal(err)
365 }
366
367 if len(keys) != 1 {
368 t.Fatal("Failed to read key with a revoked user id")
369 }
370
371 identities := keys[0].Identities
372
373 if numIdentities, numExpected := len(identities), 2; numIdentities != numExpected {
374 t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
375 }
376
377 firstIdentity, found := identities["Golang Gopher <[email protected]>"]
378 if !found {
379 t.Errorf("missing first identity")
380 }
381
382 secondIdentity, found := identities["Golang Gopher <[email protected]>"]
383 if !found {
384 t.Errorf("missing second identity")
385 }
386
387 if !firstIdentity.Revoked(time.Now()) {
388 t.Errorf("expected first identity to be revoked")
389 }
390
391 if secondIdentity.Revoked(time.Now()) {
392 t.Errorf("expected second identity not to be revoked")
393 }
394
395 const timeFormat = "2006-01-02"
396 time1, _ := time.Parse(timeFormat, "2020-01-01")
397
398 if _, found := keys[0].SigningKey(time1); !found {
399 t.Errorf("Expected SigningKey to return a signing key when first User IDs is revoked")
400 }
401
402 if _, found := keys[0].EncryptionKey(time1); !found {
403 t.Errorf("Expected EncryptionKey to return an encryption key when first User IDs is revoked")
404 }
405 }
406
407 func TestOnlyUserIDRevoked(t *testing.T) {
408 // This key contains 1 UID which is revoked (but also has a self-signature)
409 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithOnlyUserIDRevoked))
410 if err != nil {
411 t.Fatal(err)
412 }
413
414 if len(keys) != 1 {
415 t.Fatal("Failed to read key with a revoked user id")
416 }
417
418 identities := keys[0].Identities
419
420 if numIdentities, numExpected := len(identities), 1; numIdentities != numExpected {
421 t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
422 }
423
424 identity, found := identities["Revoked Primary User ID <[email protected]>"]
425 if !found {
426 t.Errorf("missing identity")
427 }
428
429 if !identity.Revoked(time.Now()) {
430 t.Errorf("expected identity to be revoked")
431 }
432
433 if _, found := keys[0].SigningKey(time.Now()); found {
434 t.Errorf("Expected SigningKey not to return a signing key when the only User IDs is revoked")
435 }
436
437 if _, found := keys[0].EncryptionKey(time.Now()); found {
438 t.Errorf("Expected EncryptionKey not to return an encryption key when the only User IDs is revoked")
439 }
440 }
441
442 func TestDummyPrivateKey(t *testing.T) {
443 // This public key has a signing subkey, but has a dummy placeholder
444 // instead of the real private key. It's used in scenarios where the
445 // main private key is withheld and only signing is allowed (e.g. build
446 // servers).
447 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(onlySubkeyNoPrivateKey))
448 if err != nil {
449 t.Fatal(err)
450 }
451 if len(keys) != 1 {
452 t.Errorf("Failed to accept key with dummy private key, %d", len(keys))
453 }
454 if !keys[0].PrivateKey.Dummy() {
455 t.Errorf("Primary private key should be marked as a dummy key")
456 }
457 if len(keys[0].Subkeys) != 1 {
458 t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
459 }
460
461 // Test serialization of stub private key via entity.SerializePrivate().
462 var buf bytes.Buffer
463 w, err := armor.Encode(&buf, PrivateKeyType, nil)
464 if err != nil {
465 t.Errorf("Failed top initialise armored key writer")
466 }
467 err = keys[0].SerializePrivateWithoutSigning(w, nil)
468 if err != nil {
469 t.Errorf("Failed to serialize entity")
470 }
471 if w.Close() != nil {
472 t.Errorf("Failed to close writer for armored key")
473 }
474
475 keys, err = ReadArmoredKeyRing(bytes.NewBufferString(buf.String()))
476 if err != nil {
477 t.Fatal(err)
478 }
479 if len(keys) != 1 {
480 t.Errorf("Failed to accept key with dummy private key, %d", len(keys))
481 }
482 if !keys[0].PrivateKey.Dummy() {
483 t.Errorf("Primary private key should be marked as a dummy key after serialisation")
484 }
485 if len(keys[0].Subkeys) != 1 {
486 t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
487 }
488 }
489
490 // TestExternallyRevokableKey attempts to load and parse a key with a third party revocation permission.
491 func TestExternallyRevocableKey(t *testing.T) {
492 kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex))
493 if err != nil {
494 t.Fatal(err)
495 }
496
497 // The 0xA42704B92866382A key can be revoked by 0xBE3893CB843D0FE70C
498 // according to this signature that appears within the key:
499 // :signature packet: algo 1, keyid A42704B92866382A
500 // version 4, created 1396409682, md5len 0, sigclass 0x1f
501 // digest algo 2, begin of digest a9 84
502 // hashed subpkt 2 len 4 (sig created 2014-04-02)
503 // hashed subpkt 12 len 22 (revocation key: c=80 a=1 f=CE094AA433F7040BB2DDF0BE3893CB843D0FE70C)
504 // hashed subpkt 7 len 1 (not revocable)
505 // subpkt 16 len 8 (issuer key ID A42704B92866382A)
506 // data: [1024 bits]
507
508 id := uint64(0xA42704B92866382A)
509 keys := kring.KeysById(id)
510 if len(keys) != 1 {
511 t.Errorf("Expected to find key id %X, but got %d matches", id, len(keys))
512 }
513 }
514
515 func TestKeyRevocation(t *testing.T) {
516 kring, err := ReadKeyRing(readerFromHex(revokedKeyHex))
517 if err != nil {
518 t.Fatal(err)
519 }
520
521 if len(kring) != 1 {
522 t.Fatal("Failed to read key with a sub key")
523 }
524
525 // revokedKeyHex contains these keys:
526 // pub 1024R/9A34F7C0 2014-03-25 [revoked: 2014-03-25]
527 // sub 1024R/1BA3CD60 2014-03-25 [revoked: 2014-03-25]
528 ids := []uint64{0xA401D9F09A34F7C0, 0x5CD3BE0A1BA3CD60}
529
530 for _, id := range ids {
531 keys := kring.KeysById(id)
532 if len(keys) != 1 {
533 t.Errorf("Expected KeysById to find revoked key %X, but got %d matches", id, len(keys))
534 }
535 keys = kring.KeysByIdUsage(id, 0)
536 if len(keys) != 1 {
537 t.Errorf("Expected KeysByIdUsage to find revoked key %X, but got %d matches", id, len(keys))
538 }
539 }
540
541 signingkey, found := kring[0].SigningKey(time.Now())
542 if found {
543 t.Errorf("Expected SigningKey not to return a signing key for a revoked key, got %X", signingkey.PublicKey.KeyId)
544 }
545
546 encryptionkey, found := kring[0].EncryptionKey(time.Now())
547 if found {
548 t.Errorf("Expected EncryptionKey not to return an encryption key for a revoked key, got %X", encryptionkey.PublicKey.KeyId)
549 }
550 }
551
552 func TestKeyWithRevokedSubKey(t *testing.T) {
553 // This key contains a revoked sub key:
554 // pub rsa1024/0x4CBD826C39074E38 2018-06-14 [SC]
555 // Key fingerprint = 3F95 169F 3FFA 7D3F 2B47 6F0C 4CBD 826C 3907 4E38
556 // uid Golang Gopher <[email protected]>
557 // sub rsa1024/0x945DB1AF61D85727 2018-06-14 [S] [revoked: 2018-06-14]
558
559 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKey))
560 if err != nil {
561 t.Fatal(err)
562 }
563
564 if len(keys) != 1 {
565 t.Fatal("Failed to read key with a sub key")
566 }
567
568 identity := keys[0].Identities["Golang Gopher <[email protected]>"]
569 // Test for an issue where Subkey Binding Signatures (RFC 4880 5.2.1) were added to the identity
570 // preceding the Subkey Packet if the Subkey Packet was followed by more than one signature.
571 // For example, the current key has the following layout:
572 // PUBKEY UID SELFSIG SUBKEY REV SELFSIG
573 // The last SELFSIG would be added to the UID's signatures. This is wrong.
574 if numSigs, numExpected := len(identity.Signatures), 1; numSigs != numExpected {
575 t.Fatalf("got %d signatures, expected %d", numSigs, numExpected)
576 }
577
578 if numSubKeys, numExpected := len(keys[0].Subkeys), 1; numSubKeys != numExpected {
579 t.Fatalf("got %d subkeys, expected %d", numSubKeys, numExpected)
580 }
581
582 subKey := keys[0].Subkeys[0]
583 if subKey.Sig == nil {
584 t.Fatalf("subkey signature is nil")
585 }
586
587 }
588
589 func TestSubkeyRevocation(t *testing.T) {
590 kring, err := ReadKeyRing(readerFromHex(revokedSubkeyHex))
591 if err != nil {
592 t.Fatal(err)
593 }
594
595 if len(kring) != 1 {
596 t.Fatal("Failed to read key with a sub key")
597 }
598
599 // revokedSubkeyHex contains these keys:
600 // pub 1024R/4EF7E4BECCDE97F0 2014-03-25
601 // sub 1024R/D63636E2B96AE423 2014-03-25
602 // sub 1024D/DBCE4EE19529437F 2014-03-25
603 // sub 1024R/677815E371C2FD23 2014-03-25 [revoked: 2014-03-25]
604 validKeys := []uint64{0x4EF7E4BECCDE97F0, 0xD63636E2B96AE423, 0xDBCE4EE19529437F}
605 encryptionKey := uint64(0xD63636E2B96AE423)
606 revokedKey := uint64(0x677815E371C2FD23)
607
608 for _, id := range validKeys {
609 keys := kring.KeysById(id)
610 if len(keys) != 1 {
611 t.Errorf("Expected KeysById to find key %X, but got %d matches", id, len(keys))
612 }
613 keys = kring.KeysByIdUsage(id, 0)
614 if len(keys) != 1 {
615 t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", id, len(keys))
616 }
617 if id == encryptionKey {
618 key, found := kring[0].EncryptionKey(time.Now())
619 if !found || key.PublicKey.KeyId != id {
620 t.Errorf("Expected EncryptionKey to find key %X", id)
621 }
622 } else {
623 _, found := kring[0].SigningKeyById(time.Now(), id)
624 if !found {
625 t.Errorf("Expected SigningKeyById to find key %X", id)
626 }
627 }
628 }
629
630 keys := kring.KeysById(revokedKey)
631 if len(keys) != 1 {
632 t.Errorf("Expected KeysById to find key %X, but got %d matches", revokedKey, len(keys))
633 }
634
635 keys = kring.KeysByIdUsage(revokedKey, 0)
636 if len(keys) != 1 {
637 t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", revokedKey, len(keys))
638 }
639
640 signingkey, found := kring[0].SigningKeyById(time.Now(), revokedKey)
641 if found {
642 t.Errorf("Expected SigningKeyById not to return an encryption key for a revoked key, got %X", signingkey.PublicKey.KeyId)
643 }
644 }
645
646 func TestKeyWithSubKeyAndBadSelfSigOrder(t *testing.T) {
647 // This key was altered so that the self signatures following the
648 // subkey are in a sub-optimal order.
649 //
650 // Note: Should someone have to create a similar key again, look into
651 // gpgsplit, gpg --dearmor, and gpg --enarmor.
652 //
653 // The packet ordering is the following:
654 // PUBKEY UID UIDSELFSIG SUBKEY SELFSIG1 SELFSIG2
655 //
656 // Where:
657 // SELFSIG1 expires on 2018-06-14 and was created first
658 // SELFSIG2 does not expire and was created after SELFSIG1
659 //
660 // Test for RFC 4880 5.2.3.3:
661 // > An implementation that encounters multiple self-signatures on the
662 // > same object may resolve the ambiguity in any way it sees fit, but it
663 // > is RECOMMENDED that priority be given to the most recent self-
664 // > signature.
665 //
666 // This means that we should keep SELFSIG2.
667
668 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKeyAndBadSelfSigOrder))
669 if err != nil {
670 t.Fatal(err)
671 }
672
673 if len(keys) != 1 {
674 t.Fatal("Failed to read key with a sub key and a bad selfsig packet order")
675 }
676
677 key := keys[0]
678
679 if numKeys, expected := len(key.Subkeys), 1; numKeys != expected {
680 t.Fatalf("Read %d subkeys, expected %d", numKeys, expected)
681 }
682
683 subKey := key.Subkeys[0]
684
685 if lifetime := subKey.Sig.KeyLifetimeSecs; lifetime != nil {
686 t.Errorf("The signature has a key lifetime (%d), but it should be nil", *lifetime)
687 }
688
689 }
690
691 func TestKeyUsage(t *testing.T) {
692 kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex))
693 if err != nil {
694 t.Fatal(err)
695 }
696
697 // subkeyUsageHex contains these keys:
698 // pub 1024R/2866382A created: 2014-04-01 expires: never usage: SC
699 // sub 1024R/936C9153 created: 2014-04-01 expires: never usage: E
700 // sub 1024R/64D5F5BB created: 2014-04-02 expires: never usage: E
701 // sub 1024D/BC0BA992 created: 2014-04-02 expires: never usage: S
702 certifiers := []uint64{0xA42704B92866382A}
703 signers := []uint64{0xA42704B92866382A, 0x42CE2C64BC0BA992}
704 encrypters := []uint64{0x09C0C7D9936C9153, 0xC104E98664D5F5BB}
705
706 for _, id := range certifiers {
707 keys := kring.KeysByIdUsage(id, packet.KeyFlagCertify)
708 if len(keys) == 1 {
709 if keys[0].PublicKey.KeyId != id {
710 t.Errorf("Expected to find certifier key id %X, but got %X", id, keys[0].PublicKey.KeyId)
711 }
712 } else {
713 t.Errorf("Expected one match for certifier key id %X, but got %d matches", id, len(keys))
714 }
715 }
716
717 for _, id := range signers {
718 keys := kring.KeysByIdUsage(id, packet.KeyFlagSign)
719 if len(keys) == 1 {
720 if keys[0].PublicKey.KeyId != id {
721 t.Errorf("Expected to find signing key id %X, but got %X", id, keys[0].PublicKey.KeyId)
722 }
723 } else {
724 t.Errorf("Expected one match for signing key id %X, but got %d matches", id, len(keys))
725 }
726
727 // This keyring contains no encryption keys that are also good for signing.
728 keys = kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications)
729 if len(keys) != 0 {
730 t.Errorf("Unexpected match for encryption key id %X", id)
731 }
732 }
733
734 for _, id := range encrypters {
735 keys := kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications)
736 if len(keys) == 1 {
737 if keys[0].PublicKey.KeyId != id {
738 t.Errorf("Expected to find encryption key id %X, but got %X", id, keys[0].PublicKey.KeyId)
739 }
740 } else {
741 t.Errorf("Expected one match for encryption key id %X, but got %d matches", id, len(keys))
742 }
743
744 // This keyring contains no encryption keys that are also good for signing.
745 keys = kring.KeysByIdUsage(id, packet.KeyFlagSign)
746 if len(keys) != 0 {
747 t.Errorf("Unexpected match for signing key id %X", id)
748 }
749 }
750 }
751
752 func TestIdVerification(t *testing.T) {
753 kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex))
754 if err != nil {
755 t.Fatal(err)
756 }
757 if err := kring[1].PrivateKey.Decrypt([]byte("passphrase")); err != nil {
758 t.Fatal(err)
759 }
760
761 const signedIdentity = "Test Key 1 (RSA)"
762 const signerIdentity = "Test Key 2 (RSA, encrypted private key)"
763 config := &packet.Config{SigLifetimeSecs: 128, SigningIdentity: signerIdentity}
764 if err := kring[0].SignIdentity(signedIdentity, kring[1], config); err != nil {
765 t.Fatal(err)
766 }
767
768 ident, ok := kring[0].Identities[signedIdentity]
769 if !ok {
770 t.Fatal("signed identity missing from key after signing")
771 }
772
773 checked := false
774 for _, sig := range ident.Signatures {
775 if sig.IssuerKeyId == nil || *sig.IssuerKeyId != kring[1].PrimaryKey.KeyId {
776 continue
777 }
778
779 if err := kring[1].PrimaryKey.VerifyUserIdSignature(signedIdentity, kring[0].PrimaryKey, sig); err != nil {
780 t.Fatalf("error verifying new identity signature: %s", err)
781 }
782
783 if sig.SignerUserId == nil || *sig.SignerUserId != signerIdentity {
784 t.Fatalf("wrong or nil signer identity")
785 }
786
787 if sig.SigExpired(time.Now()) {
788 t.Fatalf("signature is expired")
789 }
790
791 if !sig.SigExpired(time.Now().Add(129 * time.Second)) {
792 t.Fatalf("signature has invalid expiration")
793 }
794
795 checked = true
796 break
797 }
798
799 if !checked {
800 t.Fatal("didn't find identity signature in Entity")
801 }
802 }
803
804 func TestNewEntityWithDefaultHash(t *testing.T) {
805 for _, hash := range hashes {
806 c := &packet.Config{
807 DefaultHash: hash,
808 }
809 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", c)
810 if hash == crypto.SHA1 {
811 if err == nil {
812 t.Fatal("should fail on SHA1 key creation")
813 }
814 continue
815 }
816
817 if err != nil {
818 t.Fatal(err)
819 }
820
821 for _, identity := range entity.Identities {
822 prefs := identity.SelfSignature.PreferredHash
823 if len(prefs) == 0 {
824 t.Fatal("didn't find a preferred hash list in self signature")
825 }
826 ph := hashToHashId(c.DefaultHash)
827 if prefs[0] != ph {
828 t.Fatalf("Expected preferred hash to be %d, got %d", ph, prefs[0])
829 }
830 }
831 }
832 }
833
834 func TestNewEntityNilConfigPreferredHash(t *testing.T) {
835 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
836 if err != nil {
837 t.Fatal(err)
838 }
839
840 for _, identity := range entity.Identities {
841 prefs := identity.SelfSignature.PreferredHash
842 if len(prefs) != 1 {
843 t.Fatal("expected preferred hashes list to be [SHA256]")
844 }
845 }
846 }
847
848 func TestNewEntityCorrectName(t *testing.T) {
849 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
850 if err != nil {
851 t.Fatal(err)
852 }
853 if len(entity.Identities) != 1 {
854 t.Fatalf("len(entity.Identities) = %d, want 1", len(entity.Identities))
855 }
856 var got string
857 for _, i := range entity.Identities {
858 got = i.Name
859 }
860 want := "Golang Gopher (Test Key) <[email protected]>"
861 if got != want {
862 t.Fatalf("Identity.Name = %q, want %q", got, want)
863 }
864 }
865
866 func TestNewEntityWithDefaultCipher(t *testing.T) {
867 for _, cipher := range ciphers {
868 c := &packet.Config{
869 DefaultCipher: cipher,
870 }
871 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", c)
872 if err != nil {
873 t.Fatal(err)
874 }
875
876 for _, identity := range entity.Identities {
877 prefs := identity.SelfSignature.PreferredSymmetric
878 if len(prefs) == 0 {
879 t.Fatal("didn't find a preferred cipher list")
880 }
881 if prefs[0] != uint8(c.DefaultCipher) {
882 t.Fatalf("Expected preferred cipher to be %d, got %d", uint8(c.DefaultCipher), prefs[0])
883 }
884 }
885 }
886 }
887
888 func TestNewEntityNilConfigPreferredSymmetric(t *testing.T) {
889 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
890 if err != nil {
891 t.Fatal(err)
892 }
893
894 for _, identity := range entity.Identities {
895 prefs := identity.SelfSignature.PreferredSymmetric
896 if len(prefs) != 1 || prefs[0] != algorithm.AES128.Id() {
897 t.Fatal("expected preferred ciphers list to be [AES128]")
898 }
899 }
900 }
901
902 func TestNewEntityWithDefaultAead(t *testing.T) {
903 for _, aeadMode := range aeadModes {
904 cfg := &packet.Config{
905 AEADConfig: &packet.AEADConfig{
906 DefaultMode: aeadMode,
907 },
908 }
909 entity, err := NewEntity("Botvinnik", "1.e4", "[email protected]", cfg)
910 if err != nil {
911 t.Fatal(err)
912 }
913
914 for _, identity := range entity.Identities {
915 if len(identity.SelfSignature.PreferredCipherSuites) == 0 {
916 t.Fatal("didn't find a preferred mode in self signature")
917 }
918 cipher := identity.SelfSignature.PreferredCipherSuites[0][0]
919 if cipher != uint8(cfg.Cipher()) {
920 t.Fatalf("Expected preferred cipher to be %d, got %d",
921 uint8(cfg.Cipher()),
922 identity.SelfSignature.PreferredCipherSuites[0][0])
923 }
924 mode := identity.SelfSignature.PreferredCipherSuites[0][1]
925 if mode != uint8(cfg.AEAD().DefaultMode) {
926 t.Fatalf("Expected preferred mode to be %d, got %d",
927 uint8(cfg.AEAD().DefaultMode),
928 identity.SelfSignature.PreferredCipherSuites[0][1])
929 }
930 }
931 }
932 }
933
934 func TestNewEntityPublicSerialization(t *testing.T) {
935 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
936 if err != nil {
937 t.Fatal(err)
938 }
939 serializedEntity := bytes.NewBuffer(nil)
940 err = entity.Serialize(serializedEntity)
941 if err != nil {
942 t.Fatal(err)
943 }
944
945 _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
946 if err != nil {
947 t.Fatal(err)
948 }
949 }
950
951 func TestNewEntityPrivateSerialization(t *testing.T) {
952 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
953 if err != nil {
954 t.Fatal(err)
955 }
956 serializedEntity := bytes.NewBuffer(nil)
957 err = entity.SerializePrivateWithoutSigning(serializedEntity, nil)
958 if err != nil {
959 t.Fatal(err)
960 }
961
962 _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
963 if err != nil {
964 t.Fatal(err)
965 }
966 }
967
968 func TestNotationPacket(t *testing.T) {
969 config := &packet.Config{
970 NonDeterministicSignaturesViaNotation: packet.BoolPointer(false),
971 }
972 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithNotation))
973 if err != nil {
974 t.Fatal(err)
975 }
976
977 assertNotationPackets(t, keys)
978
979 serializedEntity := bytes.NewBuffer(nil)
980 err = keys[0].SerializePrivate(serializedEntity, config)
981 if err != nil {
982 t.Fatal(err)
983 }
984
985 keys, err = ReadKeyRing(serializedEntity)
986 if err != nil {
987 t.Fatal(err)
988 }
989
990 assertNotationPackets(t, keys)
991 }
992
993 func assertNotationPackets(t *testing.T, keys EntityList) {
994 if len(keys) != 1 {
995 t.Errorf("Failed to accept key, %d", len(keys))
996 }
997
998 identity := keys[0].Identities["Test <[email protected]>"]
999
1000 if numSigs, numExpected := len(identity.Signatures), 1; numSigs != numExpected {
1001 t.Fatalf("got %d signatures, expected %d", numSigs, numExpected)
1002 }
1003
1004 notations := identity.Signatures[0].Notations
1005 if numNotations, numExpected := len(notations), 2; numNotations != numExpected {
1006 t.Fatalf("got %d Notation Data subpackets, expected %d", numNotations, numExpected)
1007 }
1008
1009 if notations[0].IsHumanReadable != true {
1010 t.Fatalf("got false, expected true")
1011 }
1012
1013 if notations[0].Name != "[email protected]" {
1014 t.Fatalf("got %s, expected [email protected]", notations[0].Name)
1015 }
1016
1017 if string(notations[0].Value) != "test" {
1018 t.Fatalf("got %s, expected \"test\"", string(notations[0].Value))
1019 }
1020
1021 if notations[1].IsHumanReadable != false {
1022 t.Fatalf("got true, expected false")
1023 }
1024
1025 if notations[1].Name != "[email protected]" {
1026 t.Fatalf("got %s, expected [email protected]", notations[1].Name)
1027 }
1028
1029 if !bytes.Equal(notations[1].Value, []byte{0, 1, 2, 3}) {
1030 t.Fatalf("got %s, expected {0, 1, 2, 3}", string(notations[1].Value))
1031 }
1032 }
1033
1034 func TestEntityPrivateSerialization(t *testing.T) {
1035 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKeyBlock))
1036 if err != nil {
1037 t.Fatal(err)
1038 }
1039
1040 for _, entity := range keys {
1041 serializedEntity := bytes.NewBuffer(nil)
1042 err = entity.SerializePrivateWithoutSigning(serializedEntity, nil)
1043 if err != nil {
1044 t.Fatal(err)
1045 }
1046
1047 _, err := ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
1048 if err != nil {
1049 t.Fatal(err)
1050 }
1051 }
1052 }
1053
1054 func TestAddUserId(t *testing.T) {
1055 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1056 if err != nil {
1057 t.Fatal(err)
1058 }
1059
1060 err = entity.AddUserId("Golang Gopher", "Test Key", "[email protected]", nil)
1061 if err != nil {
1062 t.Fatal(err)
1063 }
1064
1065 err = entity.AddUserId("Golang Gopher", "Test Key", "[email protected]", nil)
1066 if err != nil {
1067 t.Fatal(err)
1068 }
1069
1070 ignore_err := entity.AddUserId("Golang Gopher", "Test Key", "[email protected]", nil)
1071 if ignore_err == nil {
1072 t.Fatal(err)
1073 }
1074
1075 if len(entity.Identities) != 3 {
1076 t.Fatalf("Expected 3 id, got %d", len(entity.Identities))
1077 }
1078
1079 for _, sk := range entity.Identities {
1080 err = entity.PrimaryKey.VerifyUserIdSignature(sk.UserId.Id, entity.PrimaryKey, sk.SelfSignature)
1081 if err != nil {
1082 t.Errorf("Invalid subkey signature: %v", err)
1083 }
1084 }
1085
1086 serializedEntity := bytes.NewBuffer(nil)
1087 if err := entity.SerializePrivate(serializedEntity, nil); err != nil {
1088 t.Fatal(err)
1089 }
1090
1091 _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
1092 if err != nil {
1093 t.Fatal(err)
1094 }
1095 }
1096 func TestAddSubkey(t *testing.T) {
1097 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1098 if err != nil {
1099 t.Fatal(err)
1100 }
1101
1102 err = entity.AddSigningSubkey(nil)
1103 if err != nil {
1104 t.Fatal(err)
1105 }
1106
1107 err = entity.AddEncryptionSubkey(nil)
1108 if err != nil {
1109 t.Fatal(err)
1110 }
1111
1112 if len(entity.Subkeys) != 3 {
1113 t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
1114 }
1115
1116 for _, sk := range entity.Subkeys {
1117 err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
1118 if err != nil {
1119 t.Errorf("Invalid subkey signature: %v", err)
1120 }
1121 }
1122
1123 serializedEntity := bytes.NewBuffer(nil)
1124 if err := entity.SerializePrivate(serializedEntity, nil); err != nil {
1125 t.Fatal(err)
1126 }
1127
1128 _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
1129 if err != nil {
1130 t.Fatal(err)
1131 }
1132 }
1133
1134 func TestAddSubkeySerialized(t *testing.T) {
1135 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1136 if err != nil {
1137 t.Fatal(err)
1138 }
1139
1140 err = entity.AddSigningSubkey(nil)
1141 if err != nil {
1142 t.Fatal(err)
1143 }
1144
1145 err = entity.AddEncryptionSubkey(nil)
1146 if err != nil {
1147 t.Fatal(err)
1148 }
1149
1150 serializedEntity := bytes.NewBuffer(nil)
1151 if err = entity.SerializePrivateWithoutSigning(serializedEntity, nil); err != nil {
1152 t.Fatal(err)
1153 }
1154
1155 entity, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
1156 if err != nil {
1157 t.Fatal(err)
1158 }
1159
1160 if len(entity.Subkeys) != 3 {
1161 t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
1162 }
1163
1164 for _, sk := range entity.Subkeys {
1165 err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
1166 if err != nil {
1167 t.Errorf("Invalid subkey signature: %v", err)
1168 }
1169 }
1170 }
1171
1172 func TestAddSubkeyWithConfig(t *testing.T) {
1173 c := &packet.Config{
1174 DefaultHash: crypto.SHA512,
1175 Algorithm: packet.PubKeyAlgoEdDSA,
1176 }
1177 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1178 if err != nil {
1179 t.Fatal(err)
1180 }
1181
1182 err = entity.AddSigningSubkey(c)
1183 if err != nil {
1184 t.Fatal(err)
1185 }
1186
1187 err = entity.AddEncryptionSubkey(c)
1188 if err != nil {
1189 t.Fatal(err)
1190 }
1191
1192 if len(entity.Subkeys) != 3 {
1193 t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
1194 }
1195
1196 if entity.Subkeys[1].PublicKey.PubKeyAlgo != packet.PubKeyAlgoEdDSA {
1197 t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoEdDSA,
1198 entity.Subkeys[1].PublicKey.PubKeyAlgo)
1199 }
1200
1201 if entity.Subkeys[2].PublicKey.PubKeyAlgo != packet.PubKeyAlgoECDH {
1202 t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoECDH,
1203 entity.Subkeys[2].PublicKey.PubKeyAlgo)
1204 }
1205
1206 if entity.Subkeys[1].Sig.Hash != c.DefaultHash {
1207 t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
1208 entity.Subkeys[1].Sig.Hash)
1209 }
1210
1211 if entity.Subkeys[1].Sig.EmbeddedSignature.Hash != c.DefaultHash {
1212 t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
1213 entity.Subkeys[1].Sig.EmbeddedSignature.Hash)
1214 }
1215
1216 if entity.Subkeys[2].Sig.Hash != c.DefaultHash {
1217 t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
1218 entity.Subkeys[2].Sig.Hash)
1219 }
1220
1221 for _, sk := range entity.Subkeys {
1222 err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
1223 if err != nil {
1224 t.Errorf("Invalid subkey signature: %v", err)
1225 }
1226 }
1227
1228 serializedEntity := bytes.NewBuffer(nil)
1229 if err = entity.SerializePrivate(serializedEntity, nil); err != nil {
1230 t.Fatal(err)
1231 }
1232
1233 _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
1234 if err != nil {
1235 t.Fatal(err)
1236 }
1237 }
1238
1239 func TestAddSubkeyWithConfigSerialized(t *testing.T) {
1240 c := &packet.Config{
1241 DefaultHash: crypto.SHA512,
1242 Algorithm: packet.PubKeyAlgoEdDSA,
1243 }
1244 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1245 if err != nil {
1246 t.Fatal(err)
1247 }
1248
1249 err = entity.AddSigningSubkey(c)
1250 if err != nil {
1251 t.Fatal(err)
1252 }
1253
1254 err = entity.AddEncryptionSubkey(c)
1255 if err != nil {
1256 t.Fatal(err)
1257 }
1258
1259 serializedEntity := bytes.NewBuffer(nil)
1260 if err := entity.SerializePrivateWithoutSigning(serializedEntity, nil); err != nil {
1261 t.Fatal(err)
1262 }
1263
1264 entity, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
1265 if err != nil {
1266 t.Fatal(err)
1267 }
1268
1269 if len(entity.Subkeys) != 3 {
1270 t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
1271 }
1272
1273 if entity.Subkeys[1].PublicKey.PubKeyAlgo != packet.PubKeyAlgoEdDSA {
1274 t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoEdDSA,
1275 entity.Subkeys[1].PublicKey.PubKeyAlgo)
1276 }
1277
1278 if entity.Subkeys[2].PublicKey.PubKeyAlgo != packet.PubKeyAlgoECDH {
1279 t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoECDH,
1280 entity.Subkeys[2].PublicKey.PubKeyAlgo)
1281 }
1282
1283 if entity.Subkeys[1].Sig.Hash != c.DefaultHash {
1284 t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
1285 entity.Subkeys[1].Sig.Hash)
1286 }
1287
1288 if entity.Subkeys[1].Sig.EmbeddedSignature.Hash != c.DefaultHash {
1289 t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
1290 entity.Subkeys[1].Sig.EmbeddedSignature.Hash)
1291 }
1292
1293 if entity.Subkeys[2].Sig.Hash != c.DefaultHash {
1294 t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
1295 entity.Subkeys[2].Sig.Hash)
1296 }
1297
1298 for _, sk := range entity.Subkeys {
1299 err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
1300 if err != nil {
1301 t.Errorf("Invalid subkey signature: %v", err)
1302 }
1303 }
1304 }
1305
1306 func TestRevokeKey(t *testing.T) {
1307 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1308 if err != nil {
1309 t.Fatal(err)
1310 }
1311
1312 err = entity.RevokeKey(packet.NoReason, "Key revocation", nil)
1313 if err != nil {
1314 t.Fatal(err)
1315 }
1316
1317 if len(entity.Revocations) == 0 {
1318 t.Fatal("Revocation signature missing from entity")
1319 }
1320
1321 for _, r := range entity.Revocations {
1322 err = entity.PrimaryKey.VerifyRevocationSignature(r)
1323 if err != nil {
1324 t.Errorf("Invalid revocation: %v", err)
1325 }
1326 }
1327 }
1328
1329 func TestRevokeKeyWithConfig(t *testing.T) {
1330 c := &packet.Config{
1331 DefaultHash: crypto.SHA512,
1332 }
1333
1334 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", &packet.Config{
1335 Algorithm: packet.PubKeyAlgoEdDSA,
1336 })
1337 if err != nil {
1338 t.Fatal(err)
1339 }
1340
1341 err = entity.RevokeKey(packet.NoReason, "Key revocation", c)
1342 if err != nil {
1343 t.Fatal(err)
1344 }
1345
1346 if len(entity.Revocations) == 0 {
1347 t.Fatal("Revocation signature missing from entity")
1348 }
1349
1350 if entity.Revocations[0].Hash != c.DefaultHash {
1351 t.Fatalf("Expected signature hash method: %v, got: %v", c.DefaultHash,
1352 entity.Revocations[0].Hash)
1353 }
1354
1355 for _, r := range entity.Revocations {
1356 err = entity.PrimaryKey.VerifyRevocationSignature(r)
1357 if err != nil {
1358 t.Errorf("Invalid revocation: %v", err)
1359 }
1360 }
1361 }
1362
1363 func TestRevokeSubkey(t *testing.T) {
1364 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1365 if err != nil {
1366 t.Fatal(err)
1367 }
1368
1369 sk := &entity.Subkeys[0]
1370 err = entity.RevokeSubkey(sk, packet.NoReason, "Key revocation", nil)
1371 if err != nil {
1372 t.Fatal(err)
1373 }
1374
1375 if len(entity.Subkeys[0].Revocations) != 1 {
1376 t.Fatalf("Expected 1 subkey revocation signature, got %v", len(sk.Revocations))
1377 }
1378
1379 revSig := entity.Subkeys[0].Revocations[0]
1380
1381 err = entity.PrimaryKey.VerifySubkeyRevocationSignature(revSig, sk.PublicKey)
1382 if err != nil {
1383 t.Fatal(err)
1384 }
1385
1386 if revSig.RevocationReason == nil {
1387 t.Fatal("Revocation reason was not set")
1388 }
1389 if revSig.RevocationReasonText == "" {
1390 t.Fatal("Revocation reason text was not set")
1391 }
1392
1393 serializedEntity := bytes.NewBuffer(nil)
1394 if err := entity.SerializePrivate(serializedEntity, nil); err != nil {
1395 t.Fatal(err)
1396 }
1397
1398 // Make sure revocation reason subpackets are not lost during serialization.
1399 newEntity, err := ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
1400 if err != nil {
1401 t.Fatal(err)
1402 }
1403
1404 if newEntity.Subkeys[0].Revocations[0].RevocationReason == nil {
1405 t.Fatal("Revocation reason lost after serialization of entity")
1406 }
1407 if newEntity.Subkeys[0].Revocations[0].RevocationReasonText == "" {
1408 t.Fatal("Revocation reason text lost after serialization of entity")
1409 }
1410 }
1411
1412 func TestRevokeSubkeyWithAnotherEntity(t *testing.T) {
1413 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1414 if err != nil {
1415 t.Fatal(err)
1416 }
1417
1418 sk := entity.Subkeys[0]
1419
1420 newEntity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1421 if err != nil {
1422 t.Fatal(err)
1423 }
1424
1425 err = newEntity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", nil)
1426 if err == nil {
1427 t.Fatal("Entity was able to revoke a subkey owned by a different entity")
1428 }
1429 }
1430
1431 func TestRevokeSubkeyWithInvalidSignature(t *testing.T) {
1432 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1433 if err != nil {
1434 t.Fatal(err)
1435 }
1436
1437 sk := entity.Subkeys[0]
1438 sk.Sig = &packet.Signature{Version: 4}
1439
1440 err = entity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", nil)
1441 if err == nil {
1442 t.Fatal("Entity was able to revoke a subkey with invalid signature")
1443 }
1444 }
1445
1446 func TestRevokeSubkeyWithConfig(t *testing.T) {
1447 c := &packet.Config{
1448 DefaultHash: crypto.SHA512,
1449 }
1450
1451 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1452 if err != nil {
1453 t.Fatal(err)
1454 }
1455
1456 sk := entity.Subkeys[0]
1457 err = entity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", c)
1458 if err != nil {
1459 t.Fatal(err)
1460 }
1461
1462 if len(sk.Revocations) != 1 {
1463 t.Fatalf("Expected 1 subkey revocation signature, got %v", len(sk.Revocations))
1464 }
1465
1466 revSig := sk.Revocations[0]
1467
1468 if revSig.Hash != c.DefaultHash {
1469 t.Fatalf("Expected signature hash method: %v, got: %v", c.DefaultHash, revSig.Hash)
1470 }
1471
1472 err = entity.PrimaryKey.VerifySubkeyRevocationSignature(revSig, sk.PublicKey)
1473 if err != nil {
1474 t.Fatal(err)
1475 }
1476 }
1477
1478 func TestEncryptAndDecryptPrivateKeys(t *testing.T) {
1479 s2kModesToTest := []s2k.Mode{s2k.IteratedSaltedS2K, s2k.Argon2S2K}
1480
1481 entity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", nil)
1482 if err != nil {
1483 t.Fatal(err)
1484 }
1485
1486 err = entity.AddSigningSubkey(nil)
1487 if err != nil {
1488 t.Fatal(err)
1489 }
1490
1491 err = entity.AddEncryptionSubkey(nil)
1492 if err != nil {
1493 t.Fatal(err)
1494 }
1495 for _, mode := range s2kModesToTest {
1496 t.Run(fmt.Sprintf("S2KMode %d", mode), func(t *testing.T) {
1497 passphrase := []byte("password")
1498 config := &packet.Config{
1499 S2KConfig: &s2k.Config{
1500 S2KMode: mode,
1501 },
1502 }
1503 if mode == s2k.Argon2S2K {
1504 config.AEADConfig = &packet.AEADConfig{}
1505 }
1506 err = entity.EncryptPrivateKeys(passphrase, config)
1507 if err != nil {
1508 t.Fatal(err)
1509 }
1510
1511 if !entity.PrivateKey.Encrypted {
1512 t.Fatal("Expected encrypted private key")
1513 }
1514 for _, subkey := range entity.Subkeys {
1515 if !subkey.PrivateKey.Encrypted {
1516 t.Fatal("Expected encrypted private key")
1517 }
1518 }
1519
1520 err = entity.DecryptPrivateKeys(passphrase)
1521 if err != nil {
1522 t.Fatal(err)
1523 }
1524
1525 if entity.PrivateKey.Encrypted {
1526 t.Fatal("Expected plaintext private key")
1527 }
1528 for _, subkey := range entity.Subkeys {
1529 if subkey.PrivateKey.Encrypted {
1530 t.Fatal("Expected plaintext private key")
1531 }
1532 }
1533 })
1534 }
1535 }
1536
1537 func TestKeyValidateOnDecrypt(t *testing.T) {
1538 randomPassword := make([]byte, 128)
1539 _, err := rand.Read(randomPassword)
1540 if err != nil {
1541 t.Fatal(err)
1542 }
1543
1544 t.Run("RSA", func(t *testing.T) {
1545 t.Run("Hardcoded:2048 bits", func(t *testing.T) {
1546 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(rsa2048PrivateKey))
1547 if err != nil {
1548 t.Fatal("Unable to parse hardcoded key: ", err)
1549 }
1550
1551 if err := keys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
1552 t.Fatal("Unable to decrypt hardcoded key: ", err)
1553 }
1554
1555 testKeyValidateRsaOnDecrypt(t, keys[0], randomPassword)
1556 })
1557
1558 for _, bits := range []int{2048, 3072, 4096} {
1559 t.Run("Generated:"+strconv.Itoa(bits)+" bits", func(t *testing.T) {
1560 key := testGenerateRSA(t, bits)
1561 testKeyValidateRsaOnDecrypt(t, key, randomPassword)
1562 })
1563 }
1564 })
1565
1566 t.Run("ECDSA", func(t *testing.T) {
1567 t.Run("Hardcoded:NIST P-256", func(t *testing.T) {
1568 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(ecdsaPrivateKey))
1569 if err != nil {
1570 t.Fatal("Unable to parse hardcoded key: ", err)
1571 }
1572
1573 if err := keys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
1574 t.Fatal("Unable to decrypt hardcoded key: ", err)
1575 }
1576
1577 if err := keys[0].Subkeys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
1578 t.Fatal("Unable to decrypt hardcoded subkey: ", err)
1579 }
1580
1581 testKeyValidateEcdsaOnDecrypt(t, keys[0], randomPassword)
1582 })
1583
1584 ecdsaCurves := map[string]packet.Curve{
1585 "NIST P-256": packet.CurveNistP256,
1586 "NIST P-384": packet.CurveNistP384,
1587 "NIST P-521": packet.CurveNistP521,
1588 "Brainpool P-256": packet.CurveBrainpoolP256,
1589 "Brainpool P-384": packet.CurveBrainpoolP384,
1590 "Brainpool P-512": packet.CurveBrainpoolP512,
1591 "SecP256k1": packet.CurveSecP256k1,
1592 }
1593
1594 for name, curveType := range ecdsaCurves {
1595 t.Run("Generated:"+name, func(t *testing.T) {
1596 key := testGenerateEC(t, packet.PubKeyAlgoECDSA, curveType)
1597 testKeyValidateEcdsaOnDecrypt(t, key, randomPassword)
1598 })
1599 }
1600 })
1601
1602 t.Run("EdDSA", func(t *testing.T) {
1603 eddsaHardcoded := map[string]string{
1604 "Curve25519": curve25519PrivateKey,
1605 "Curve448": curve448PrivateKey,
1606 }
1607
1608 for name, skData := range eddsaHardcoded {
1609 t.Run("Hardcoded:"+name, func(t *testing.T) {
1610 keys, err := ReadArmoredKeyRing(bytes.NewBufferString(skData))
1611 if err != nil {
1612 t.Fatal("Unable to parse hardcoded key: ", err)
1613 }
1614
1615 testKeyValidateEddsaOnDecrypt(t, keys[0], randomPassword)
1616 })
1617 }
1618
1619 eddsaCurves := map[string]packet.Curve{
1620 "Curve25519": packet.Curve25519,
1621 "Curve448": packet.Curve448,
1622 }
1623
1624 for name, curveType := range eddsaCurves {
1625 t.Run("Generated:"+name, func(t *testing.T) {
1626 key := testGenerateEC(t, packet.PubKeyAlgoEdDSA, curveType)
1627 testKeyValidateEddsaOnDecrypt(t, key, randomPassword)
1628 })
1629 }
1630 })
1631
1632 t.Run("DSA With El Gamal Subkey", func(t *testing.T) {
1633 testKeyValidateDsaElGamalOnDecrypt(t, randomPassword)
1634 })
1635 }
1636
1637 func testGenerateRSA(t *testing.T, bits int) *Entity {
1638 config := &packet.Config{Algorithm: packet.PubKeyAlgoRSA, RSABits: bits}
1639 rsaEntity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", config)
1640 if err != nil {
1641 t.Fatal(err)
1642 }
1643
1644 return rsaEntity
1645 }
1646
1647 func testKeyValidateRsaOnDecrypt(t *testing.T, rsaEntity *Entity, password []byte) {
1648 var err error
1649 rsaPrimaryKey := rsaEntity.PrivateKey
1650 if err = rsaPrimaryKey.Encrypt(password); err != nil {
1651 t.Fatal(err)
1652 }
1653 if err = rsaPrimaryKey.Decrypt(password); err != nil {
1654 t.Fatal("Valid RSA key was marked as invalid: ", err)
1655 }
1656
1657 if err = rsaPrimaryKey.Encrypt(password); err != nil {
1658 t.Fatal(err)
1659 }
1660
1661 // Corrupt public modulo n in primary key
1662 n := rsaPrimaryKey.PublicKey.PublicKey.(*rsa.PublicKey).N
1663 rsaPrimaryKey.PublicKey.PublicKey.(*rsa.PublicKey).N = new(big.Int).Add(n, big.NewInt(2))
1664 err = rsaPrimaryKey.Decrypt(password)
1665 if _, ok := err.(errors.KeyInvalidError); !ok {
1666 t.Fatal("Failed to detect invalid RSA key")
1667 }
1668 }
1669
1670 func testGenerateEC(t *testing.T, algorithm packet.PublicKeyAlgorithm, curve packet.Curve) *Entity {
1671 config := &packet.Config{Algorithm: algorithm, Curve: curve}
1672 rsaEntity, err := NewEntity("Golang Gopher", "Test Key", "[email protected]", config)
1673 if err != nil {
1674 t.Fatal(err)
1675 }
1676
1677 return rsaEntity
1678 }
1679
1680 func testKeyValidateEcdsaOnDecrypt(t *testing.T, ecdsaKey *Entity, password []byte) {
1681 var err error
1682 ecdsaPrimaryKey := ecdsaKey.PrivateKey
1683
1684 if err = ecdsaPrimaryKey.Encrypt(password); err != nil {
1685 t.Fatal(err)
1686 }
1687
1688 if err := ecdsaPrimaryKey.Decrypt(password); err != nil {
1689 t.Fatal("Valid ECDSA key was marked as invalid: ", err)
1690 }
1691
1692 if err = ecdsaPrimaryKey.Encrypt(password); err != nil {
1693 t.Fatal(err)
1694 }
1695
1696 // Corrupt public X in primary key
1697 X := ecdsaPrimaryKey.PublicKey.PublicKey.(*ecdsa.PublicKey).X
1698 ecdsaPrimaryKey.PublicKey.PublicKey.(*ecdsa.PublicKey).X = new(big.Int).Add(X, big.NewInt(1))
1699 err = ecdsaPrimaryKey.Decrypt(password)
1700 if _, ok := err.(errors.KeyInvalidError); !ok {
1701 t.Fatal("Failed to detect invalid ECDSA key")
1702 }
1703
1704 // ECDH
1705 ecdsaSubkey := ecdsaKey.Subkeys[0].PrivateKey
1706 if err = ecdsaSubkey.Encrypt(password); err != nil {
1707 t.Fatal(err)
1708 }
1709
1710 if err := ecdsaSubkey.Decrypt(password); err != nil {
1711 t.Fatal("Valid ECDH key was marked as invalid: ", err)
1712 }
1713
1714 if err = ecdsaSubkey.Encrypt(password); err != nil {
1715 t.Fatal(err)
1716 }
1717
1718 // Corrupt public X in subkey
1719 ecdsaSubkey.PublicKey.PublicKey.(*ecdh.PublicKey).Point[5] ^= 1
1720
1721 err = ecdsaSubkey.Decrypt(password)
1722 if _, ok := err.(errors.KeyInvalidError); !ok {
1723 t.Fatal("Failed to detect invalid ECDH key")
1724 }
1725 }
1726
1727 func testKeyValidateEddsaOnDecrypt(t *testing.T, eddsaEntity *Entity, password []byte) {
1728 var err error
1729
1730 eddsaPrimaryKey := eddsaEntity.PrivateKey // already encrypted
1731 if err = eddsaPrimaryKey.Encrypt(password); err != nil {
1732 t.Fatal(err)
1733 }
1734
1735 if err := eddsaPrimaryKey.Decrypt(password); err != nil {
1736 t.Fatal("Valid EdDSA key was marked as invalid: ", err)
1737 }
1738
1739 if err = eddsaPrimaryKey.Encrypt(password); err != nil {
1740 t.Fatal(err)
1741 }
1742
1743 pubKey := *eddsaPrimaryKey.PublicKey.PublicKey.(*eddsa.PublicKey)
1744 pubKey.X[10] ^= 1
1745 err = eddsaPrimaryKey.Decrypt(password)
1746 if _, ok := err.(errors.KeyInvalidError); !ok {
1747 t.Fatal("Failed to detect invalid EdDSA key")
1748 }
1749
1750 // ECDH
1751 ecdhSubkey := eddsaEntity.Subkeys[len(eddsaEntity.Subkeys)-1].PrivateKey
1752 if err = ecdhSubkey.Encrypt(password); err != nil {
1753 t.Fatal(err)
1754 }
1755
1756 if err := ecdhSubkey.Decrypt(password); err != nil {
1757 t.Fatal("Valid ECDH key was marked as invalid: ", err)
1758 }
1759
1760 if err = ecdhSubkey.Encrypt(password); err != nil {
1761 t.Fatal(err)
1762 }
1763
1764 // Corrupt public X in subkey
1765 ecdhSubkey.PublicKey.PublicKey.(*ecdh.PublicKey).Point[5] ^= 1
1766 err = ecdhSubkey.Decrypt(password)
1767 if _, ok := err.(errors.KeyInvalidError); !ok {
1768 t.Fatal("Failed to detect invalid ECDH key")
1769 }
1770 }
1771
1772 // ...the legacy bits
1773 func testKeyValidateDsaElGamalOnDecrypt(t *testing.T, randomPassword []byte) {
1774 var err error
1775
1776 dsaKeys, err := ReadArmoredKeyRing(bytes.NewBufferString(dsaPrivateKeyWithElGamalSubkey))
1777 if err != nil {
1778 t.Fatal(err)
1779 }
1780 dsaPrimaryKey := dsaKeys[0].PrivateKey // already encrypted
1781 if err := dsaPrimaryKey.Decrypt([]byte("password")); err != nil {
1782 t.Fatal("Valid DSA key was marked as invalid: ", err)
1783 }
1784
1785 if err = dsaPrimaryKey.Encrypt(randomPassword); err != nil {
1786 t.Fatal(err)
1787 }
1788 // corrupt DSA generator
1789 G := dsaPrimaryKey.PublicKey.PublicKey.(*dsa.PublicKey).G
1790 dsaPrimaryKey.PublicKey.PublicKey.(*dsa.PublicKey).G = new(big.Int).Add(G, big.NewInt(1))
1791 err = dsaPrimaryKey.Decrypt(randomPassword)
1792 if _, ok := err.(errors.KeyInvalidError); !ok {
1793 t.Fatal("Failed to detect invalid DSA key")
1794 }
1795
1796 // ElGamal
1797 elGamalSubkey := dsaKeys[0].Subkeys[0].PrivateKey // already encrypted
1798 if err := elGamalSubkey.Decrypt([]byte("password")); err != nil {
1799 t.Fatal("Valid ElGamal key was marked as invalid: ", err)
1800 }
1801
1802 if err = elGamalSubkey.Encrypt(randomPassword); err != nil {
1803 t.Fatal(err)
1804 }
1805
1806 // corrupt ElGamal generator
1807 G = elGamalSubkey.PublicKey.PublicKey.(*elgamal.PublicKey).G
1808 elGamalSubkey.PublicKey.PublicKey.(*elgamal.PublicKey).G = new(big.Int).Add(G, big.NewInt(1))
1809 err = elGamalSubkey.Decrypt(randomPassword)
1810 if _, ok := err.(errors.KeyInvalidError); !ok {
1811 t.Fatal("Failed to detect invalid ElGamal key")
1812 }
1813 }
1814
1815 var foreignKeysv4 = []string{
1816 v4Key25519,
1817 }
1818
1819 func TestReadPrivateForeignV4Key(t *testing.T) {
1820 for _, str := range foreignKeysv4 {
1821 kring, err := ReadArmoredKeyRing(strings.NewReader(str))
1822 if err != nil {
1823 t.Fatal(err)
1824 }
1825 checkV4Key(t, kring[0])
1826 }
1827 }
1828
1829 func checkV4Key(t *testing.T, ent *Entity) {
1830 key := ent.PrimaryKey
1831 if key.Version != 4 {
1832 t.Errorf("wrong key version %d", key.Version)
1833 }
1834 if len(key.Fingerprint) != 20 {
1835 t.Errorf("Wrong fingerprint length: %d", len(key.Fingerprint))
1836 }
1837 signatures := ent.Revocations
1838 for _, id := range ent.Identities {
1839 signatures = append(signatures, id.SelfSignature)
1840 signatures = append(signatures, id.Signatures...)
1841 }
1842 for _, sig := range signatures {
1843 if sig == nil {
1844 continue
1845 }
1846 if sig.Version != 4 {
1847 t.Errorf("wrong signature version %d", sig.Version)
1848 }
1849 fgptLen := len(sig.IssuerFingerprint)
1850 if fgptLen != 20 {
1851 t.Errorf("Wrong fingerprint length in signature: %d", fgptLen)
1852 }
1853 }
1854 }
1855
1856 // Should not panic (generated with go-fuzz)
1857 func TestCorruptKeys(t *testing.T) {
1858 data := `-----BEGIN PGP PUBLIC KEY BLOCK00000
1859
1860 mQ00BF00000BCAD0000000000000000000000000000000000000000000000000
1861 0000000000000000000000000000000000000000000000000000000000000000
1862 0000000000000000000000000000000000000000000000000000000000000000
1863 0000000000000000000000000000000000000000000000000000000000000000
1864 0000000000000000000000000000000000000000000000000000000000000000
1865 000000000000000000000000000000000000ABE000G0Dn000000000000000000iQ00BB0BAgAGBCG00000`
1866 ReadArmoredKeyRing(strings.NewReader(data))
1867 }
1868
1869 func TestGenerateRSAKeyPLessThanQ(t *testing.T) {
1870 // RFC 9580 section 5.5.5.1 requires p < q for RSA keys.
1871 checkKey := func(t *testing.T, key *rsa.PrivateKey, err error) {
1872 t.Helper()
1873 if err != nil {
1874 t.Fatal(err)
1875 }
1876 // Primes[1] is serialized as p and Primes[0] as q.
1877 if key.Primes[1].Cmp(key.Primes[0]) >= 0 {
1878 t.Fatal("expected p < q")
1879 }
1880 if err := key.Validate(); err != nil {
1881 t.Fatal(err)
1882 }
1883 }
1884
1885 t.Run("enforceRSAPrimeOrder", func(t *testing.T) {
1886 key, err := rsa.GenerateKey(rand.Reader, 2048)
1887 if err != nil {
1888 t.Fatal(err)
1889 }
1890 // Force p > q so that the swap is always exercised.
1891 if key.Primes[0].Cmp(key.Primes[1]) > 0 {
1892 key.Primes[0], key.Primes[1] = key.Primes[1], key.Primes[0]
1893 key.Precomputed = rsa.PrecomputedValues{}
1894 key.Precompute()
1895 }
1896 enforceRSAPrimeOrder(key)
1897 checkKey(t, key, nil)
1898 })
1899
1900 t.Run("generateRSAKey", func(t *testing.T) {
1901 key, err := generateRSAKey(rand.Reader, 2048)
1902 checkKey(t, key, err)
1903 })
1904
1905 t.Run("generateRSAKeyWithPrimes", func(t *testing.T) {
1906 key, err := generateRSAKeyWithPrimes(rand.Reader, 2, 2048, nil)
1907 checkKey(t, key, err)
1908 })
1909 }
1910
1911 func testAddMlkemSubkey(t *testing.T, entity *Entity, v6Keys bool) {
1912 var err error
1913
1914 asymmAlgos := map[string]packet.PublicKeyAlgorithm{
1915 "Mlkem768_X25519": packet.PubKeyAlgoMlkem768X25519,
1916 "Mlkem1024_X448": packet.PubKeyAlgoMlkem1024X448,
1917 }
1918
1919 for name, algo := range asymmAlgos {
1920 // Remove existing subkeys
1921 entity.Subkeys = []Subkey{}
1922
1923 t.Run(name, func(t *testing.T) {
1924 kyberConfig := &packet.Config{
1925 DefaultHash: crypto.SHA512,
1926 Algorithm: algo,
1927 V6Keys: v6Keys,
1928 Time: func() time.Time {
1929 parsed, _ := time.Parse("2006-01-02", "2013-07-01")
1930 return parsed
1931 },
1932 }
1933
1934 err = entity.AddEncryptionSubkey(kyberConfig)
1935 if err != nil {
1936 t.Fatal(err)
1937 }
1938
1939 if len(entity.Subkeys) != 1 {
1940 t.Fatalf("Expected 1 subkey, got %d", len(entity.Subkeys))
1941 }
1942
1943 if entity.Subkeys[0].PublicKey.PubKeyAlgo != algo {
1944 t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoEdDSA,
1945 entity.Subkeys[0].PublicKey.PubKeyAlgo)
1946 }
1947
1948 if entity.Subkeys[0].PublicKey.Version != entity.PrivateKey.Version {
1949 t.Fatalf("Expected subkey version: %d, got: %d", entity.PrivateKey.Version,
1950 entity.Subkeys[0].PublicKey.Version)
1951 }
1952
1953 serializedEntity := bytes.NewBuffer(nil)
1954 err = entity.SerializePrivate(serializedEntity, nil)
1955 if err != nil {
1956 t.Fatalf("Failed to serialize entity: %s", err)
1957 }
1958
1959 read, err := ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
1960 if err != nil {
1961 t.Fatal(err)
1962 }
1963
1964 if len(read.Subkeys) != 1 {
1965 t.Fatalf("Expected 1 subkey, got %d", len(entity.Subkeys))
1966 }
1967
1968 if read.Subkeys[0].PublicKey.PubKeyAlgo != algo {
1969 t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoEdDSA,
1970 entity.Subkeys[0].PublicKey.PubKeyAlgo)
1971 }
1972 })
1973 }
1974 }