File: keys_test.go

package info (click to toggle)
golang-github-protonmail-go-crypto 1.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,932 kB
  • sloc: makefile: 10
file content (1867 lines) | stat: -rw-r--r-- 54,370 bytes parent folder | download | duplicates (3)
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
package openpgp

import (
	"bytes"
	"crypto"
	"crypto/dsa"
	"crypto/rand"
	"crypto/rsa"
	"fmt"
	"math/big"
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/ProtonMail/go-crypto/openpgp/armor"
	"github.com/ProtonMail/go-crypto/openpgp/ecdh"
	"github.com/ProtonMail/go-crypto/openpgp/ecdsa"
	"github.com/ProtonMail/go-crypto/openpgp/eddsa"
	"github.com/ProtonMail/go-crypto/openpgp/elgamal"
	"github.com/ProtonMail/go-crypto/openpgp/errors"
	"github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
	"github.com/ProtonMail/go-crypto/openpgp/packet"
	"github.com/ProtonMail/go-crypto/openpgp/s2k"
)

var hashes = []crypto.Hash{
	crypto.SHA1,
	crypto.SHA224,
	crypto.SHA256,
	crypto.SHA384,
	crypto.SHA512,
	crypto.SHA3_256,
	crypto.SHA3_512,
}

var ciphers = []packet.CipherFunction{
	packet.Cipher3DES,
	packet.CipherCAST5,
	packet.CipherAES128,
	packet.CipherAES192,
	packet.CipherAES256,
}

var aeadModes = []packet.AEADMode{
	packet.AEADModeOCB,
	packet.AEADModeEAX,
	packet.AEADModeGCM,
}

func TestKeyExpiry(t *testing.T) {
	kring, err := ReadKeyRing(readerFromHex(expiringKeyHex))
	if err != nil {
		t.Fatal(err)
	}
	entity := kring[0]

	const timeFormat = "2006-01-02"
	time1, _ := time.Parse(timeFormat, "2013-07-02")

	// The expiringKeyHex key is structured as:
	//
	// pub  1024R/5E237D8C  created: 2013-07-01                      expires: 2013-07-31  usage: SC
	// sub  1024R/1ABB25A0  created: 2013-07-01 23:11:07 +0200 CEST  expires: 2013-07-08  usage: E
	// sub  1024R/96A672F5  created: 2013-07-01 23:11:23 +0200 CEST  expires: 2013-07-31  usage: E
	//
	// So this should select the newest, non-expired encryption key.
	key, ok := entity.EncryptionKey(time1)
	if !ok {
		t.Fatal("No encryption key found")
	}
	if id, expected := key.PublicKey.KeyIdShortString(), "CD3D39FF"; id != expected {
		t.Errorf("Expected key %s at time %s, but got key %s", expected, time1.Format(timeFormat), id)
	}

	// Once the first encryption subkey has expired, the second should be
	// selected.
	time2, _ := time.Parse(timeFormat, "2013-07-09")
	key, _ = entity.EncryptionKey(time2)
	if id, expected := key.PublicKey.KeyIdShortString(), "CD3D39FF"; id != expected {
		t.Errorf("Expected key %s at time %s, but got key %s", expected, time2.Format(timeFormat), id)
	}

	// Once all the keys have expired, nothing should be returned.
	time3, _ := time.Parse(timeFormat, "2013-08-01")
	if key, ok := entity.EncryptionKey(time3); ok {
		t.Errorf("Expected no key at time %s, but got key %s", time3.Format(timeFormat), key.PublicKey.KeyIdShortString())
	}
}

// https://tests.sequoia-pgp.org/#Certificate_expiration
// P _ U f
func TestExpiringPrimaryUIDKey(t *testing.T) {
	// P _ U f
	kring, err := ReadArmoredKeyRing(bytes.NewBufferString((expiringPrimaryUIDKey)))
	if err != nil {
		t.Fatal(err)
	}
	entity := kring[0]

	const timeFormat string = "2006-01-02"
	const expectedKeyID string = "015E7330"

	// Before the primary UID has expired, the primary key should be returned.
	time1, err := time.Parse(timeFormat, "2022-02-05")
	if err != nil {
		t.Fatal(err)
	}
	key, found := entity.SigningKey(time1)
	if !found {
		t.Errorf("Signing subkey %s not found at time %s", expectedKeyID, time1.Format(timeFormat))
	} else if observedKeyID := key.PublicKey.KeyIdShortString(); observedKeyID != expectedKeyID {
		t.Errorf("Expected key %s at time %s, but got key %s", expectedKeyID, time1.Format(timeFormat), observedKeyID)
	}

	// After the primary UID has expired, nothing should be returned.
	time2, err := time.Parse(timeFormat, "2022-02-06")
	if err != nil {
		t.Fatal(err)
	}
	if key, ok := entity.SigningKey(time2); ok {
		t.Errorf("Expected no key at time %s, but got key %s", time2.Format(timeFormat), key.PublicKey.KeyIdShortString())
	}
}

func TestReturnNewestUnexpiredSigningSubkey(t *testing.T) {
	// Make a master key.
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	// First signing subkey does not expire.
	err = entity.AddSigningSubkey(nil)
	if err != nil {
		t.Fatal(err)
	}
	// Get the first signing subkey (added after the default encryption subkey).
	subkey1 := entity.Subkeys[1]

	// Second signing subkey expires in a day.
	err = entity.AddSigningSubkey(&packet.Config{
		Time: func() time.Time {
			return time.Now().Add(1 * time.Second)
		},
		KeyLifetimeSecs: 24 * 60 * 60,
	})
	if err != nil {
		t.Fatal(err)
	}
	// Get the second signing subkey.
	subkey2 := entity.Subkeys[2]

	// Before second signing subkey has expired, it should be returned.
	time1 := time.Now().Add(2 * time.Second)
	expected := subkey2.PublicKey.KeyIdShortString()
	subkey, found := entity.SigningKey(time1)
	if !found {
		t.Errorf("Signing subkey %s not found at time %s", expected, time1.Format(time.UnixDate))
	}
	observed := subkey.PublicKey.KeyIdShortString()
	if observed != expected {
		t.Errorf("Expected key %s at time %s, but got key %s", expected, time1.Format(time.UnixDate), observed)
	}

	// After the second signing subkey has expired, the first one should be returned.
	time2 := time1.AddDate(0, 0, 2)
	expected = subkey1.PublicKey.KeyIdShortString()
	subkey, found = entity.SigningKey(time2)
	if !found {
		t.Errorf("Signing subkey %s not found at time %s", expected, time2.Format(time.UnixDate))
	}
	observed = subkey.PublicKey.KeyIdShortString()
	if observed != expected {
		t.Errorf("Expected key %s at time %s, but got key %s", expected, time2.Format(time.UnixDate), observed)
	}
}

func TestSignatureExpiry(t *testing.T) {
	// Make a master key, and attach it to a keyring.
	var keyring EntityList
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}
	keyring = append(keyring, entity)

	// Make a signature that never expires.
	var signatureWriter1 bytes.Buffer
	const input string = "Hello, world!"
	message := strings.NewReader(input)
	err = ArmoredDetachSign(&signatureWriter1, entity, message, nil)
	if err != nil {
		t.Fatal(err)
	}

	// Make a signature that expires in a day.
	var signatureWriter2 bytes.Buffer
	message = strings.NewReader(input)
	err = ArmoredDetachSign(&signatureWriter2, entity, message, &packet.Config{
		SigLifetimeSecs: 24 * 60 * 60,
	})
	if err != nil {
		t.Fatal(err)
	}

	// Make a time that is day after tomorrow.
	futureTime := func() time.Time {
		return time.Now().AddDate(0, 0, 2)
	}

	// Make a signature that was created in the future.
	var signatureWriter3 bytes.Buffer
	message = strings.NewReader(input)
	err = ArmoredDetachSign(&signatureWriter3, entity, message, &packet.Config{
		Time: futureTime,
	})
	if err != nil {
		t.Fatal(err)
	}

	// Check that the first signature has not expired day after tomorrow.
	message = strings.NewReader(input)
	signatureReader1 := strings.NewReader(signatureWriter1.String())
	_, err = CheckArmoredDetachedSignature(keyring, message, signatureReader1, &packet.Config{
		Time: futureTime,
	})
	if err != nil {
		t.Fatal(err)
	}

	// Check that the second signature has expired day after tomorrow.
	message = strings.NewReader(input)
	signatureReader2 := strings.NewReader(signatureWriter2.String())
	const expectedErr string = "openpgp: signature expired"
	_, observedErr := CheckArmoredDetachedSignature(keyring, message, signatureReader2, &packet.Config{
		Time: futureTime,
	})
	if observedErr.Error() != expectedErr {
		t.Errorf("Expected error '%s', but got error '%s'", expectedErr, observedErr)
	}

	// Check that the third signature is also considered expired even now.
	message = strings.NewReader(input)
	signatureReader3 := strings.NewReader(signatureWriter3.String())
	_, observedErr = CheckArmoredDetachedSignature(keyring, message, signatureReader3, nil)
	if observedErr.Error() != expectedErr {
		t.Errorf("Expected error '%s', but got error '%s'", expectedErr, observedErr)
	}
}

func TestMissingCrossSignature(t *testing.T) {
	// This public key has a signing subkey, but the subkey does not
	// contain a cross-signature.
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(missingCrossSignatureKey))
	if len(keys) != 0 {
		t.Errorf("Accepted key with missing cross signature")
	}
	if err == nil {
		t.Fatal("Failed to detect error in keyring with missing cross signature")
	}
	structural, ok := err.(errors.StructuralError)
	if !ok {
		t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err)
	}
	const expectedMsg = "signing subkey is missing cross-signature"
	if !strings.Contains(string(structural), expectedMsg) {
		t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg)
	}
}

func TestInvalidCrossSignature(t *testing.T) {
	// This public key has a signing subkey, and the subkey has an
	// embedded cross-signature. However, the cross-signature does
	// not correctly validate over the primary and subkey.
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(invalidCrossSignatureKey))
	if len(keys) != 0 {
		t.Errorf("Accepted key with invalid cross signature")
	}
	if err == nil {
		t.Fatal("Failed to detect error in keyring with an invalid cross signature")
	}
	structural, ok := err.(errors.StructuralError)
	if !ok {
		t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err)
	}
	const expectedMsg = "subkey signature invalid"
	if !strings.Contains(string(structural), expectedMsg) {
		t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg)
	}
}

func TestGoodCrossSignature(t *testing.T) {
	// This public key has a signing subkey, and the subkey has an
	// embedded cross-signature which correctly validates over the
	// primary and subkey.
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(goodCrossSignatureKey))
	if err != nil {
		t.Fatal(err)
	}
	if len(keys) != 1 {
		t.Errorf("Failed to accept key with good cross signature, %d", len(keys))
	}
	if len(keys[0].Subkeys) != 1 {
		t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
	}
}

func TestRevokedUserID(t *testing.T) {
	// This key contains 2 UIDs, one of which is revoked and has no valid self-signature:
	// [ultimate] (1)  Golang Gopher <no-reply@golang.com>
	// [ revoked] (2)  Golang Gopher <revoked@golang.com>
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(revokedUserIDKey))
	if err != nil {
		t.Fatal(err)
	}

	if len(keys) != 1 {
		t.Fatal("Failed to read key with a revoked user id")
	}

	identities := keys[0].Identities

	if numIdentities, numExpected := len(identities), 2; numIdentities != numExpected {
		t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
	}

	firstIdentity, found := identities["Golang Gopher <no-reply@golang.com>"]
	if !found {
		t.Errorf("missing first identity")
	}

	secondIdentity, found := identities["Golang Gopher <revoked@golang.com>"]
	if !found {
		t.Errorf("missing second identity")
	}

	if firstIdentity.Revoked(time.Now()) {
		t.Errorf("expected first identity not to be revoked")
	}

	if !secondIdentity.Revoked(time.Now()) {
		t.Errorf("expected second identity to be revoked")
	}

	const timeFormat = "2006-01-02"
	time1, _ := time.Parse(timeFormat, "2020-01-01")

	if _, found := keys[0].SigningKey(time1); !found {
		t.Errorf("Expected SigningKey to return a signing key when one User IDs is revoked")
	}

	if _, found := keys[0].EncryptionKey(time1); !found {
		t.Errorf("Expected EncryptionKey to return an encryption key when one User IDs is revoked")
	}
}

func TestFirstUserIDRevoked(t *testing.T) {
	// Same test as above, but with the User IDs reversed:
	// [ revoked] (1)  Golang Gopher <revoked@golang.com>
	// [ultimate] (2)  Golang Gopher <no-reply@golang.com>
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithFirstUserIDRevoked))
	if err != nil {
		t.Fatal(err)
	}

	if len(keys) != 1 {
		t.Fatal("Failed to read key with a revoked user id")
	}

	identities := keys[0].Identities

	if numIdentities, numExpected := len(identities), 2; numIdentities != numExpected {
		t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
	}

	firstIdentity, found := identities["Golang Gopher <revoked@golang.com>"]
	if !found {
		t.Errorf("missing first identity")
	}

	secondIdentity, found := identities["Golang Gopher <no-reply@golang.com>"]
	if !found {
		t.Errorf("missing second identity")
	}

	if !firstIdentity.Revoked(time.Now()) {
		t.Errorf("expected first identity to be revoked")
	}

	if secondIdentity.Revoked(time.Now()) {
		t.Errorf("expected second identity not to be revoked")
	}

	const timeFormat = "2006-01-02"
	time1, _ := time.Parse(timeFormat, "2020-01-01")

	if _, found := keys[0].SigningKey(time1); !found {
		t.Errorf("Expected SigningKey to return a signing key when first User IDs is revoked")
	}

	if _, found := keys[0].EncryptionKey(time1); !found {
		t.Errorf("Expected EncryptionKey to return an encryption key when first User IDs is revoked")
	}
}

func TestOnlyUserIDRevoked(t *testing.T) {
	// This key contains 1 UID which is revoked (but also has a self-signature)
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithOnlyUserIDRevoked))
	if err != nil {
		t.Fatal(err)
	}

	if len(keys) != 1 {
		t.Fatal("Failed to read key with a revoked user id")
	}

	identities := keys[0].Identities

	if numIdentities, numExpected := len(identities), 1; numIdentities != numExpected {
		t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
	}

	identity, found := identities["Revoked Primary User ID <revoked@key.com>"]
	if !found {
		t.Errorf("missing identity")
	}

	if !identity.Revoked(time.Now()) {
		t.Errorf("expected identity to be revoked")
	}

	if _, found := keys[0].SigningKey(time.Now()); found {
		t.Errorf("Expected SigningKey not to return a signing key when the only User IDs is revoked")
	}

	if _, found := keys[0].EncryptionKey(time.Now()); found {
		t.Errorf("Expected EncryptionKey not to return an encryption key when the only User IDs is revoked")
	}
}

func TestDummyPrivateKey(t *testing.T) {
	// This public key has a signing subkey, but has a dummy placeholder
	// instead of the real private key. It's used in scenarios where the
	// main private key is withheld and only signing is allowed (e.g. build
	// servers).
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(onlySubkeyNoPrivateKey))
	if err != nil {
		t.Fatal(err)
	}
	if len(keys) != 1 {
		t.Errorf("Failed to accept key with dummy private key, %d", len(keys))
	}
	if !keys[0].PrivateKey.Dummy() {
		t.Errorf("Primary private key should be marked as a dummy key")
	}
	if len(keys[0].Subkeys) != 1 {
		t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
	}

	// Test serialization of stub private key via entity.SerializePrivate().
	var buf bytes.Buffer
	w, err := armor.Encode(&buf, PrivateKeyType, nil)
	if err != nil {
		t.Errorf("Failed top initialise armored key writer")
	}
	err = keys[0].SerializePrivateWithoutSigning(w, nil)
	if err != nil {
		t.Errorf("Failed to serialize entity")
	}
	if w.Close() != nil {
		t.Errorf("Failed to close writer for armored key")
	}

	keys, err = ReadArmoredKeyRing(bytes.NewBufferString(buf.String()))
	if err != nil {
		t.Fatal(err)
	}
	if len(keys) != 1 {
		t.Errorf("Failed to accept key with dummy private key, %d", len(keys))
	}
	if !keys[0].PrivateKey.Dummy() {
		t.Errorf("Primary private key should be marked as a dummy key after serialisation")
	}
	if len(keys[0].Subkeys) != 1 {
		t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
	}
}

// TestExternallyRevokableKey attempts to load and parse a key with a third party revocation permission.
func TestExternallyRevocableKey(t *testing.T) {
	kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex))
	if err != nil {
		t.Fatal(err)
	}

	// The 0xA42704B92866382A key can be revoked by 0xBE3893CB843D0FE70C
	// according to this signature that appears within the key:
	// :signature packet: algo 1, keyid A42704B92866382A
	//    version 4, created 1396409682, md5len 0, sigclass 0x1f
	//    digest algo 2, begin of digest a9 84
	//    hashed subpkt 2 len 4 (sig created 2014-04-02)
	//    hashed subpkt 12 len 22 (revocation key: c=80 a=1 f=CE094AA433F7040BB2DDF0BE3893CB843D0FE70C)
	//    hashed subpkt 7 len 1 (not revocable)
	//    subpkt 16 len 8 (issuer key ID A42704B92866382A)
	//    data: [1024 bits]

	id := uint64(0xA42704B92866382A)
	keys := kring.KeysById(id)
	if len(keys) != 1 {
		t.Errorf("Expected to find key id %X, but got %d matches", id, len(keys))
	}
}

func TestKeyRevocation(t *testing.T) {
	kring, err := ReadKeyRing(readerFromHex(revokedKeyHex))
	if err != nil {
		t.Fatal(err)
	}

	if len(kring) != 1 {
		t.Fatal("Failed to read key with a sub key")
	}

	// revokedKeyHex contains these keys:
	// pub   1024R/9A34F7C0 2014-03-25 [revoked: 2014-03-25]
	// sub   1024R/1BA3CD60 2014-03-25 [revoked: 2014-03-25]
	ids := []uint64{0xA401D9F09A34F7C0, 0x5CD3BE0A1BA3CD60}

	for _, id := range ids {
		keys := kring.KeysById(id)
		if len(keys) != 1 {
			t.Errorf("Expected KeysById to find revoked key %X, but got %d matches", id, len(keys))
		}
		keys = kring.KeysByIdUsage(id, 0)
		if len(keys) != 1 {
			t.Errorf("Expected KeysByIdUsage to find revoked key %X, but got %d matches", id, len(keys))
		}
	}

	signingkey, found := kring[0].SigningKey(time.Now())
	if found {
		t.Errorf("Expected SigningKey not to return a signing key for a revoked key, got %X", signingkey.PublicKey.KeyId)
	}

	encryptionkey, found := kring[0].EncryptionKey(time.Now())
	if found {
		t.Errorf("Expected EncryptionKey not to return an encryption key for a revoked key, got %X", encryptionkey.PublicKey.KeyId)
	}
}

func TestKeyWithRevokedSubKey(t *testing.T) {
	// This key contains a revoked sub key:
	//  pub   rsa1024/0x4CBD826C39074E38 2018-06-14 [SC]
	//        Key fingerprint = 3F95 169F 3FFA 7D3F 2B47  6F0C 4CBD 826C 3907 4E38
	//  uid   Golang Gopher <no-reply@golang.com>
	//  sub   rsa1024/0x945DB1AF61D85727 2018-06-14 [S] [revoked: 2018-06-14]

	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKey))
	if err != nil {
		t.Fatal(err)
	}

	if len(keys) != 1 {
		t.Fatal("Failed to read key with a sub key")
	}

	identity := keys[0].Identities["Golang Gopher <no-reply@golang.com>"]
	// Test for an issue where Subkey Binding Signatures (RFC 4880 5.2.1) were added to the identity
	// preceding the Subkey Packet if the Subkey Packet was followed by more than one signature.
	// For example, the current key has the following layout:
	//    PUBKEY UID SELFSIG SUBKEY REV SELFSIG
	// The last SELFSIG would be added to the UID's signatures. This is wrong.
	if numSigs, numExpected := len(identity.Signatures), 1; numSigs != numExpected {
		t.Fatalf("got %d signatures, expected %d", numSigs, numExpected)
	}

	if numSubKeys, numExpected := len(keys[0].Subkeys), 1; numSubKeys != numExpected {
		t.Fatalf("got %d subkeys, expected %d", numSubKeys, numExpected)
	}

	subKey := keys[0].Subkeys[0]
	if subKey.Sig == nil {
		t.Fatalf("subkey signature is nil")
	}

}

func TestSubkeyRevocation(t *testing.T) {
	kring, err := ReadKeyRing(readerFromHex(revokedSubkeyHex))
	if err != nil {
		t.Fatal(err)
	}

	if len(kring) != 1 {
		t.Fatal("Failed to read key with a sub key")
	}

	// revokedSubkeyHex contains these keys:
	// pub   1024R/4EF7E4BECCDE97F0 2014-03-25
	// sub   1024R/D63636E2B96AE423 2014-03-25
	// sub   1024D/DBCE4EE19529437F 2014-03-25
	// sub   1024R/677815E371C2FD23 2014-03-25 [revoked: 2014-03-25]
	validKeys := []uint64{0x4EF7E4BECCDE97F0, 0xD63636E2B96AE423, 0xDBCE4EE19529437F}
	encryptionKey := uint64(0xD63636E2B96AE423)
	revokedKey := uint64(0x677815E371C2FD23)

	for _, id := range validKeys {
		keys := kring.KeysById(id)
		if len(keys) != 1 {
			t.Errorf("Expected KeysById to find key %X, but got %d matches", id, len(keys))
		}
		keys = kring.KeysByIdUsage(id, 0)
		if len(keys) != 1 {
			t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", id, len(keys))
		}
		if id == encryptionKey {
			key, found := kring[0].EncryptionKey(time.Now())
			if !found || key.PublicKey.KeyId != id {
				t.Errorf("Expected EncryptionKey to find key %X", id)
			}
		} else {
			_, found := kring[0].SigningKeyById(time.Now(), id)
			if !found {
				t.Errorf("Expected SigningKeyById to find key %X", id)
			}
		}
	}

	keys := kring.KeysById(revokedKey)
	if len(keys) != 1 {
		t.Errorf("Expected KeysById to find key %X, but got %d matches", revokedKey, len(keys))
	}

	keys = kring.KeysByIdUsage(revokedKey, 0)
	if len(keys) != 1 {
		t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", revokedKey, len(keys))
	}

	signingkey, found := kring[0].SigningKeyById(time.Now(), revokedKey)
	if found {
		t.Errorf("Expected SigningKeyById not to return an encryption key for a revoked key, got %X", signingkey.PublicKey.KeyId)
	}
}

func TestKeyWithSubKeyAndBadSelfSigOrder(t *testing.T) {
	// This key was altered so that the self signatures following the
	// subkey are in a sub-optimal order.
	//
	// Note: Should someone have to create a similar key again, look into
	//       gpgsplit, gpg --dearmor, and gpg --enarmor.
	//
	// The packet ordering is the following:
	//    PUBKEY UID UIDSELFSIG SUBKEY SELFSIG1 SELFSIG2
	//
	// Where:
	//    SELFSIG1 expires on 2018-06-14 and was created first
	//    SELFSIG2 does not expire and was created after SELFSIG1
	//
	// Test for RFC 4880 5.2.3.3:
	// > An implementation that encounters multiple self-signatures on the
	// > same object may resolve the ambiguity in any way it sees fit, but it
	// > is RECOMMENDED that priority be given to the most recent self-
	// > signature.
	//
	// This means that we should keep SELFSIG2.

	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKeyAndBadSelfSigOrder))
	if err != nil {
		t.Fatal(err)
	}

	if len(keys) != 1 {
		t.Fatal("Failed to read key with a sub key and a bad selfsig packet order")
	}

	key := keys[0]

	if numKeys, expected := len(key.Subkeys), 1; numKeys != expected {
		t.Fatalf("Read %d subkeys, expected %d", numKeys, expected)
	}

	subKey := key.Subkeys[0]

	if lifetime := subKey.Sig.KeyLifetimeSecs; lifetime != nil {
		t.Errorf("The signature has a key lifetime (%d), but it should be nil", *lifetime)
	}

}

func TestKeyUsage(t *testing.T) {
	kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex))
	if err != nil {
		t.Fatal(err)
	}

	// subkeyUsageHex contains these keys:
	// pub  1024R/2866382A  created: 2014-04-01  expires: never       usage: SC
	// sub  1024R/936C9153  created: 2014-04-01  expires: never       usage: E
	// sub  1024R/64D5F5BB  created: 2014-04-02  expires: never       usage: E
	// sub  1024D/BC0BA992  created: 2014-04-02  expires: never       usage: S
	certifiers := []uint64{0xA42704B92866382A}
	signers := []uint64{0xA42704B92866382A, 0x42CE2C64BC0BA992}
	encrypters := []uint64{0x09C0C7D9936C9153, 0xC104E98664D5F5BB}

	for _, id := range certifiers {
		keys := kring.KeysByIdUsage(id, packet.KeyFlagCertify)
		if len(keys) == 1 {
			if keys[0].PublicKey.KeyId != id {
				t.Errorf("Expected to find certifier key id %X, but got %X", id, keys[0].PublicKey.KeyId)
			}
		} else {
			t.Errorf("Expected one match for certifier key id %X, but got %d matches", id, len(keys))
		}
	}

	for _, id := range signers {
		keys := kring.KeysByIdUsage(id, packet.KeyFlagSign)
		if len(keys) == 1 {
			if keys[0].PublicKey.KeyId != id {
				t.Errorf("Expected to find signing key id %X, but got %X", id, keys[0].PublicKey.KeyId)
			}
		} else {
			t.Errorf("Expected one match for signing key id %X, but got %d matches", id, len(keys))
		}

		// This keyring contains no encryption keys that are also good for signing.
		keys = kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications)
		if len(keys) != 0 {
			t.Errorf("Unexpected match for encryption key id %X", id)
		}
	}

	for _, id := range encrypters {
		keys := kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications)
		if len(keys) == 1 {
			if keys[0].PublicKey.KeyId != id {
				t.Errorf("Expected to find encryption key id %X, but got %X", id, keys[0].PublicKey.KeyId)
			}
		} else {
			t.Errorf("Expected one match for encryption key id %X, but got %d matches", id, len(keys))
		}

		// This keyring contains no encryption keys that are also good for signing.
		keys = kring.KeysByIdUsage(id, packet.KeyFlagSign)
		if len(keys) != 0 {
			t.Errorf("Unexpected match for signing key id %X", id)
		}
	}
}

func TestIdVerification(t *testing.T) {
	kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex))
	if err != nil {
		t.Fatal(err)
	}
	if err := kring[1].PrivateKey.Decrypt([]byte("passphrase")); err != nil {
		t.Fatal(err)
	}

	const signedIdentity = "Test Key 1 (RSA)"
	const signerIdentity = "Test Key 2 (RSA, encrypted private key)"
	config := &packet.Config{SigLifetimeSecs: 128, SigningIdentity: signerIdentity}
	if err := kring[0].SignIdentity(signedIdentity, kring[1], config); err != nil {
		t.Fatal(err)
	}

	ident, ok := kring[0].Identities[signedIdentity]
	if !ok {
		t.Fatal("signed identity missing from key after signing")
	}

	checked := false
	for _, sig := range ident.Signatures {
		if sig.IssuerKeyId == nil || *sig.IssuerKeyId != kring[1].PrimaryKey.KeyId {
			continue
		}

		if err := kring[1].PrimaryKey.VerifyUserIdSignature(signedIdentity, kring[0].PrimaryKey, sig); err != nil {
			t.Fatalf("error verifying new identity signature: %s", err)
		}

		if sig.SignerUserId == nil || *sig.SignerUserId != signerIdentity {
			t.Fatalf("wrong or nil signer identity")
		}

		if sig.SigExpired(time.Now()) {
			t.Fatalf("signature is expired")
		}

		if !sig.SigExpired(time.Now().Add(129 * time.Second)) {
			t.Fatalf("signature has invalid expiration")
		}

		checked = true
		break
	}

	if !checked {
		t.Fatal("didn't find identity signature in Entity")
	}
}

func TestNewEntityWithDefaultHash(t *testing.T) {
	for _, hash := range hashes {
		c := &packet.Config{
			DefaultHash: hash,
		}
		entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", c)
		if hash == crypto.SHA1 {
			if err == nil {
				t.Fatal("should fail on SHA1 key creation")
			}
			continue
		}

		if err != nil {
			t.Fatal(err)
		}

		for _, identity := range entity.Identities {
			prefs := identity.SelfSignature.PreferredHash
			if len(prefs) == 0 {
				t.Fatal("didn't find a preferred hash list in self signature")
			}
			ph := hashToHashId(c.DefaultHash)
			if prefs[0] != ph {
				t.Fatalf("Expected preferred hash to be %d, got %d", ph, prefs[0])
			}
		}
	}
}

func TestNewEntityNilConfigPreferredHash(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	for _, identity := range entity.Identities {
		prefs := identity.SelfSignature.PreferredHash
		if len(prefs) != 1 {
			t.Fatal("expected preferred hashes list to be [SHA256]")
		}
	}
}

func TestNewEntityCorrectName(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}
	if len(entity.Identities) != 1 {
		t.Fatalf("len(entity.Identities) = %d, want 1", len(entity.Identities))
	}
	var got string
	for _, i := range entity.Identities {
		got = i.Name
	}
	want := "Golang Gopher (Test Key) <no-reply@golang.com>"
	if got != want {
		t.Fatalf("Identity.Name = %q, want %q", got, want)
	}
}

func TestNewEntityWithDefaultCipher(t *testing.T) {
	for _, cipher := range ciphers {
		c := &packet.Config{
			DefaultCipher: cipher,
		}
		entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", c)
		if err != nil {
			t.Fatal(err)
		}

		for _, identity := range entity.Identities {
			prefs := identity.SelfSignature.PreferredSymmetric
			if len(prefs) == 0 {
				t.Fatal("didn't find a preferred cipher list")
			}
			if prefs[0] != uint8(c.DefaultCipher) {
				t.Fatalf("Expected preferred cipher to be %d, got %d", uint8(c.DefaultCipher), prefs[0])
			}
		}
	}
}

func TestNewEntityNilConfigPreferredSymmetric(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	for _, identity := range entity.Identities {
		prefs := identity.SelfSignature.PreferredSymmetric
		if len(prefs) != 1 || prefs[0] != algorithm.AES128.Id() {
			t.Fatal("expected preferred ciphers list to be [AES128]")
		}
	}
}

func TestNewEntityWithDefaultAead(t *testing.T) {
	for _, aeadMode := range aeadModes {
		cfg := &packet.Config{
			AEADConfig: &packet.AEADConfig{
				DefaultMode: aeadMode,
			},
		}
		entity, err := NewEntity("Botvinnik", "1.e4", "tal@chess.com", cfg)
		if err != nil {
			t.Fatal(err)
		}

		for _, identity := range entity.Identities {
			if len(identity.SelfSignature.PreferredCipherSuites) == 0 {
				t.Fatal("didn't find a preferred mode in self signature")
			}
			cipher := identity.SelfSignature.PreferredCipherSuites[0][0]
			if cipher != uint8(cfg.Cipher()) {
				t.Fatalf("Expected preferred cipher to be %d, got %d",
					uint8(cfg.Cipher()),
					identity.SelfSignature.PreferredCipherSuites[0][0])
			}
			mode := identity.SelfSignature.PreferredCipherSuites[0][1]
			if mode != uint8(cfg.AEAD().DefaultMode) {
				t.Fatalf("Expected preferred mode to be %d, got %d",
					uint8(cfg.AEAD().DefaultMode),
					identity.SelfSignature.PreferredCipherSuites[0][1])
			}
		}
	}
}

func TestNewEntityPublicSerialization(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}
	serializedEntity := bytes.NewBuffer(nil)
	err = entity.Serialize(serializedEntity)
	if err != nil {
		t.Fatal(err)
	}

	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
	if err != nil {
		t.Fatal(err)
	}
}

func TestNewEntityPrivateSerialization(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}
	serializedEntity := bytes.NewBuffer(nil)
	err = entity.SerializePrivateWithoutSigning(serializedEntity, nil)
	if err != nil {
		t.Fatal(err)
	}

	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
	if err != nil {
		t.Fatal(err)
	}
}

func TestNotationPacket(t *testing.T) {
	config := &packet.Config{
		NonDeterministicSignaturesViaNotation: packet.BoolPointer(false),
	}
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithNotation))
	if err != nil {
		t.Fatal(err)
	}

	assertNotationPackets(t, keys)

	serializedEntity := bytes.NewBuffer(nil)
	err = keys[0].SerializePrivate(serializedEntity, config)
	if err != nil {
		t.Fatal(err)
	}

	keys, err = ReadKeyRing(serializedEntity)
	if err != nil {
		t.Fatal(err)
	}

	assertNotationPackets(t, keys)
}

func assertNotationPackets(t *testing.T, keys EntityList) {
	if len(keys) != 1 {
		t.Errorf("Failed to accept key, %d", len(keys))
	}

	identity := keys[0].Identities["Test <test@example.com>"]

	if numSigs, numExpected := len(identity.Signatures), 1; numSigs != numExpected {
		t.Fatalf("got %d signatures, expected %d", numSigs, numExpected)
	}

	notations := identity.Signatures[0].Notations
	if numNotations, numExpected := len(notations), 2; numNotations != numExpected {
		t.Fatalf("got %d Notation Data subpackets, expected %d", numNotations, numExpected)
	}

	if notations[0].IsHumanReadable != true {
		t.Fatalf("got false, expected true")
	}

	if notations[0].Name != "text@example.com" {
		t.Fatalf("got %s, expected text@example.com", notations[0].Name)
	}

	if string(notations[0].Value) != "test" {
		t.Fatalf("got %s, expected \"test\"", string(notations[0].Value))
	}

	if notations[1].IsHumanReadable != false {
		t.Fatalf("got true, expected false")
	}

	if notations[1].Name != "binary@example.com" {
		t.Fatalf("got %s, expected binary@example.com", notations[1].Name)
	}

	if !bytes.Equal(notations[1].Value, []byte{0, 1, 2, 3}) {
		t.Fatalf("got %s, expected {0, 1, 2, 3}", string(notations[1].Value))
	}
}

func TestEntityPrivateSerialization(t *testing.T) {
	keys, err := ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKeyBlock))
	if err != nil {
		t.Fatal(err)
	}

	for _, entity := range keys {
		serializedEntity := bytes.NewBuffer(nil)
		err = entity.SerializePrivateWithoutSigning(serializedEntity, nil)
		if err != nil {
			t.Fatal(err)
		}

		_, err := ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestAddUserId(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddUserId("Golang Gopher", "Test Key", "add1---@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddUserId("Golang Gopher", "Test Key", "add2---@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	ignore_err := entity.AddUserId("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if ignore_err == nil {
		t.Fatal(err)
	}

	if len(entity.Identities) != 3 {
		t.Fatalf("Expected 3 id, got %d", len(entity.Identities))
	}

	for _, sk := range entity.Identities {
		err = entity.PrimaryKey.VerifyUserIdSignature(sk.UserId.Id, entity.PrimaryKey, sk.SelfSignature)
		if err != nil {
			t.Errorf("Invalid subkey signature: %v", err)
		}
	}

	serializedEntity := bytes.NewBuffer(nil)
	if err := entity.SerializePrivate(serializedEntity, nil); err != nil {
		t.Fatal(err)
	}

	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
	if err != nil {
		t.Fatal(err)
	}
}
func TestAddSubkey(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddSigningSubkey(nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddEncryptionSubkey(nil)
	if err != nil {
		t.Fatal(err)
	}

	if len(entity.Subkeys) != 3 {
		t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
	}

	for _, sk := range entity.Subkeys {
		err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
		if err != nil {
			t.Errorf("Invalid subkey signature: %v", err)
		}
	}

	serializedEntity := bytes.NewBuffer(nil)
	if err := entity.SerializePrivate(serializedEntity, nil); err != nil {
		t.Fatal(err)
	}

	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
	if err != nil {
		t.Fatal(err)
	}
}

func TestAddSubkeySerialized(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddSigningSubkey(nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddEncryptionSubkey(nil)
	if err != nil {
		t.Fatal(err)
	}

	serializedEntity := bytes.NewBuffer(nil)
	if err = entity.SerializePrivateWithoutSigning(serializedEntity, nil); err != nil {
		t.Fatal(err)
	}

	entity, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
	if err != nil {
		t.Fatal(err)
	}

	if len(entity.Subkeys) != 3 {
		t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
	}

	for _, sk := range entity.Subkeys {
		err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
		if err != nil {
			t.Errorf("Invalid subkey signature: %v", err)
		}
	}
}

func TestAddSubkeyWithConfig(t *testing.T) {
	c := &packet.Config{
		DefaultHash: crypto.SHA512,
		Algorithm:   packet.PubKeyAlgoEdDSA,
	}
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddSigningSubkey(c)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddEncryptionSubkey(c)
	if err != nil {
		t.Fatal(err)
	}

	if len(entity.Subkeys) != 3 {
		t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
	}

	if entity.Subkeys[1].PublicKey.PubKeyAlgo != packet.PubKeyAlgoEdDSA {
		t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoEdDSA,
			entity.Subkeys[1].PublicKey.PubKeyAlgo)
	}

	if entity.Subkeys[2].PublicKey.PubKeyAlgo != packet.PubKeyAlgoECDH {
		t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoECDH,
			entity.Subkeys[2].PublicKey.PubKeyAlgo)
	}

	if entity.Subkeys[1].Sig.Hash != c.DefaultHash {
		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
			entity.Subkeys[1].Sig.Hash)
	}

	if entity.Subkeys[1].Sig.EmbeddedSignature.Hash != c.DefaultHash {
		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
			entity.Subkeys[1].Sig.EmbeddedSignature.Hash)
	}

	if entity.Subkeys[2].Sig.Hash != c.DefaultHash {
		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
			entity.Subkeys[2].Sig.Hash)
	}

	for _, sk := range entity.Subkeys {
		err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
		if err != nil {
			t.Errorf("Invalid subkey signature: %v", err)
		}
	}

	serializedEntity := bytes.NewBuffer(nil)
	if err = entity.SerializePrivate(serializedEntity, nil); err != nil {
		t.Fatal(err)
	}

	_, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
	if err != nil {
		t.Fatal(err)
	}
}

func TestAddSubkeyWithConfigSerialized(t *testing.T) {
	c := &packet.Config{
		DefaultHash: crypto.SHA512,
		Algorithm:   packet.PubKeyAlgoEdDSA,
	}
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddSigningSubkey(c)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddEncryptionSubkey(c)
	if err != nil {
		t.Fatal(err)
	}

	serializedEntity := bytes.NewBuffer(nil)
	if err := entity.SerializePrivateWithoutSigning(serializedEntity, nil); err != nil {
		t.Fatal(err)
	}

	entity, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
	if err != nil {
		t.Fatal(err)
	}

	if len(entity.Subkeys) != 3 {
		t.Fatalf("Expected 3 subkeys, got %d", len(entity.Subkeys))
	}

	if entity.Subkeys[1].PublicKey.PubKeyAlgo != packet.PubKeyAlgoEdDSA {
		t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoEdDSA,
			entity.Subkeys[1].PublicKey.PubKeyAlgo)
	}

	if entity.Subkeys[2].PublicKey.PubKeyAlgo != packet.PubKeyAlgoECDH {
		t.Fatalf("Expected subkey algorithm: %v, got: %v", packet.PubKeyAlgoECDH,
			entity.Subkeys[2].PublicKey.PubKeyAlgo)
	}

	if entity.Subkeys[1].Sig.Hash != c.DefaultHash {
		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
			entity.Subkeys[1].Sig.Hash)
	}

	if entity.Subkeys[1].Sig.EmbeddedSignature.Hash != c.DefaultHash {
		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
			entity.Subkeys[1].Sig.EmbeddedSignature.Hash)
	}

	if entity.Subkeys[2].Sig.Hash != c.DefaultHash {
		t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
			entity.Subkeys[2].Sig.Hash)
	}

	for _, sk := range entity.Subkeys {
		err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig)
		if err != nil {
			t.Errorf("Invalid subkey signature: %v", err)
		}
	}
}

func TestRevokeKey(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.RevokeKey(packet.NoReason, "Key revocation", nil)
	if err != nil {
		t.Fatal(err)
	}

	if len(entity.Revocations) == 0 {
		t.Fatal("Revocation signature missing from entity")
	}

	for _, r := range entity.Revocations {
		err = entity.PrimaryKey.VerifyRevocationSignature(r)
		if err != nil {
			t.Errorf("Invalid revocation: %v", err)
		}
	}
}

func TestRevokeKeyWithConfig(t *testing.T) {
	c := &packet.Config{
		DefaultHash: crypto.SHA512,
	}

	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", &packet.Config{
		Algorithm: packet.PubKeyAlgoEdDSA,
	})
	if err != nil {
		t.Fatal(err)
	}

	err = entity.RevokeKey(packet.NoReason, "Key revocation", c)
	if err != nil {
		t.Fatal(err)
	}

	if len(entity.Revocations) == 0 {
		t.Fatal("Revocation signature missing from entity")
	}

	if entity.Revocations[0].Hash != c.DefaultHash {
		t.Fatalf("Expected signature hash method: %v, got: %v", c.DefaultHash,
			entity.Revocations[0].Hash)
	}

	for _, r := range entity.Revocations {
		err = entity.PrimaryKey.VerifyRevocationSignature(r)
		if err != nil {
			t.Errorf("Invalid revocation: %v", err)
		}
	}
}

func TestRevokeSubkey(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	sk := &entity.Subkeys[0]
	err = entity.RevokeSubkey(sk, packet.NoReason, "Key revocation", nil)
	if err != nil {
		t.Fatal(err)
	}

	if len(entity.Subkeys[0].Revocations) != 1 {
		t.Fatalf("Expected 1 subkey revocation signature, got %v", len(sk.Revocations))
	}

	revSig := entity.Subkeys[0].Revocations[0]

	err = entity.PrimaryKey.VerifySubkeyRevocationSignature(revSig, sk.PublicKey)
	if err != nil {
		t.Fatal(err)
	}

	if revSig.RevocationReason == nil {
		t.Fatal("Revocation reason was not set")
	}
	if revSig.RevocationReasonText == "" {
		t.Fatal("Revocation reason text was not set")
	}

	serializedEntity := bytes.NewBuffer(nil)
	if err := entity.SerializePrivate(serializedEntity, nil); err != nil {
		t.Fatal(err)
	}

	// Make sure revocation reason subpackets are not lost during serialization.
	newEntity, err := ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
	if err != nil {
		t.Fatal(err)
	}

	if newEntity.Subkeys[0].Revocations[0].RevocationReason == nil {
		t.Fatal("Revocation reason lost after serialization of entity")
	}
	if newEntity.Subkeys[0].Revocations[0].RevocationReasonText == "" {
		t.Fatal("Revocation reason text lost after serialization of entity")
	}
}

func TestRevokeSubkeyWithAnotherEntity(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	sk := entity.Subkeys[0]

	newEntity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = newEntity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", nil)
	if err == nil {
		t.Fatal("Entity was able to revoke a subkey owned by a different entity")
	}
}

func TestRevokeSubkeyWithInvalidSignature(t *testing.T) {
	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	sk := entity.Subkeys[0]
	sk.Sig = &packet.Signature{Version: 4}

	err = entity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", nil)
	if err == nil {
		t.Fatal("Entity was able to revoke a subkey with invalid signature")
	}
}

func TestRevokeSubkeyWithConfig(t *testing.T) {
	c := &packet.Config{
		DefaultHash: crypto.SHA512,
	}

	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	sk := entity.Subkeys[0]
	err = entity.RevokeSubkey(&sk, packet.NoReason, "Key revocation", c)
	if err != nil {
		t.Fatal(err)
	}

	if len(sk.Revocations) != 1 {
		t.Fatalf("Expected 1 subkey revocation signature, got %v", len(sk.Revocations))
	}

	revSig := sk.Revocations[0]

	if revSig.Hash != c.DefaultHash {
		t.Fatalf("Expected signature hash method: %v, got: %v", c.DefaultHash, revSig.Hash)
	}

	err = entity.PrimaryKey.VerifySubkeyRevocationSignature(revSig, sk.PublicKey)
	if err != nil {
		t.Fatal(err)
	}
}

func TestEncryptAndDecryptPrivateKeys(t *testing.T) {
	s2kModesToTest := []s2k.Mode{s2k.IteratedSaltedS2K, s2k.Argon2S2K}

	entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddSigningSubkey(nil)
	if err != nil {
		t.Fatal(err)
	}

	err = entity.AddEncryptionSubkey(nil)
	if err != nil {
		t.Fatal(err)
	}
	for _, mode := range s2kModesToTest {
		t.Run(fmt.Sprintf("S2KMode %d", mode), func(t *testing.T) {
			passphrase := []byte("password")
			config := &packet.Config{
				S2KConfig: &s2k.Config{
					S2KMode: mode,
				},
			}
			if mode == s2k.Argon2S2K {
				config.AEADConfig = &packet.AEADConfig{}
			}
			err = entity.EncryptPrivateKeys(passphrase, config)
			if err != nil {
				t.Fatal(err)
			}

			if !entity.PrivateKey.Encrypted {
				t.Fatal("Expected encrypted private key")
			}
			for _, subkey := range entity.Subkeys {
				if !subkey.PrivateKey.Encrypted {
					t.Fatal("Expected encrypted private key")
				}
			}

			err = entity.DecryptPrivateKeys(passphrase)
			if err != nil {
				t.Fatal(err)
			}

			if entity.PrivateKey.Encrypted {
				t.Fatal("Expected plaintext private key")
			}
			for _, subkey := range entity.Subkeys {
				if subkey.PrivateKey.Encrypted {
					t.Fatal("Expected plaintext private key")
				}
			}
		})
	}
}

func TestKeyValidateOnDecrypt(t *testing.T) {
	randomPassword := make([]byte, 128)
	_, err := rand.Read(randomPassword)
	if err != nil {
		t.Fatal(err)
	}

	t.Run("RSA", func(t *testing.T) {
		t.Run("Hardcoded:2048 bits", func(t *testing.T) {
			keys, err := ReadArmoredKeyRing(bytes.NewBufferString(rsa2048PrivateKey))
			if err != nil {
				t.Fatal("Unable to parse hardcoded key: ", err)
			}

			if err := keys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
				t.Fatal("Unable to decrypt hardcoded key: ", err)
			}

			testKeyValidateRsaOnDecrypt(t, keys[0], randomPassword)
		})

		for _, bits := range []int{2048, 3072, 4096} {
			t.Run("Generated:"+strconv.Itoa(bits)+" bits", func(t *testing.T) {
				key := testGenerateRSA(t, bits)
				testKeyValidateRsaOnDecrypt(t, key, randomPassword)
			})
		}
	})

	t.Run("ECDSA", func(t *testing.T) {
		t.Run("Hardcoded:NIST P-256", func(t *testing.T) {
			keys, err := ReadArmoredKeyRing(bytes.NewBufferString(ecdsaPrivateKey))
			if err != nil {
				t.Fatal("Unable to parse hardcoded key: ", err)
			}

			if err := keys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
				t.Fatal("Unable to decrypt hardcoded key: ", err)
			}

			if err := keys[0].Subkeys[0].PrivateKey.Decrypt([]byte("password")); err != nil {
				t.Fatal("Unable to decrypt hardcoded subkey: ", err)
			}

			testKeyValidateEcdsaOnDecrypt(t, keys[0], randomPassword)
		})

		ecdsaCurves := map[string]packet.Curve{
			"NIST P-256":      packet.CurveNistP256,
			"NIST P-384":      packet.CurveNistP384,
			"NIST P-521":      packet.CurveNistP521,
			"Brainpool P-256": packet.CurveBrainpoolP256,
			"Brainpool P-384": packet.CurveBrainpoolP384,
			"Brainpool P-512": packet.CurveBrainpoolP512,
			"SecP256k1":       packet.CurveSecP256k1,
		}

		for name, curveType := range ecdsaCurves {
			t.Run("Generated:"+name, func(t *testing.T) {
				key := testGenerateEC(t, packet.PubKeyAlgoECDSA, curveType)
				testKeyValidateEcdsaOnDecrypt(t, key, randomPassword)
			})
		}
	})

	t.Run("EdDSA", func(t *testing.T) {
		eddsaHardcoded := map[string]string{
			"Curve25519": curve25519PrivateKey,
			"Curve448":   curve448PrivateKey,
		}

		for name, skData := range eddsaHardcoded {
			t.Run("Hardcoded:"+name, func(t *testing.T) {
				keys, err := ReadArmoredKeyRing(bytes.NewBufferString(skData))
				if err != nil {
					t.Fatal("Unable to parse hardcoded key: ", err)
				}

				testKeyValidateEddsaOnDecrypt(t, keys[0], randomPassword)
			})
		}

		eddsaCurves := map[string]packet.Curve{
			"Curve25519": packet.Curve25519,
			"Curve448":   packet.Curve448,
		}

		for name, curveType := range eddsaCurves {
			t.Run("Generated:"+name, func(t *testing.T) {
				key := testGenerateEC(t, packet.PubKeyAlgoEdDSA, curveType)
				testKeyValidateEddsaOnDecrypt(t, key, randomPassword)
			})
		}
	})

	t.Run("DSA With El Gamal Subkey", func(t *testing.T) {
		testKeyValidateDsaElGamalOnDecrypt(t, randomPassword)
	})
}

func testGenerateRSA(t *testing.T, bits int) *Entity {
	config := &packet.Config{Algorithm: packet.PubKeyAlgoRSA, RSABits: bits}
	rsaEntity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", config)
	if err != nil {
		t.Fatal(err)
	}

	return rsaEntity
}

func testKeyValidateRsaOnDecrypt(t *testing.T, rsaEntity *Entity, password []byte) {
	var err error
	rsaPrimaryKey := rsaEntity.PrivateKey
	if err = rsaPrimaryKey.Encrypt(password); err != nil {
		t.Fatal(err)
	}
	if err = rsaPrimaryKey.Decrypt(password); err != nil {
		t.Fatal("Valid RSA key was marked as invalid: ", err)
	}

	if err = rsaPrimaryKey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	// Corrupt public modulo n in primary key
	n := rsaPrimaryKey.PublicKey.PublicKey.(*rsa.PublicKey).N
	rsaPrimaryKey.PublicKey.PublicKey.(*rsa.PublicKey).N = new(big.Int).Add(n, big.NewInt(2))
	err = rsaPrimaryKey.Decrypt(password)
	if _, ok := err.(errors.KeyInvalidError); !ok {
		t.Fatal("Failed to detect invalid RSA key")
	}
}

func testGenerateEC(t *testing.T, algorithm packet.PublicKeyAlgorithm, curve packet.Curve) *Entity {
	config := &packet.Config{Algorithm: algorithm, Curve: curve}
	rsaEntity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", config)
	if err != nil {
		t.Fatal(err)
	}

	return rsaEntity
}

func testKeyValidateEcdsaOnDecrypt(t *testing.T, ecdsaKey *Entity, password []byte) {
	var err error
	ecdsaPrimaryKey := ecdsaKey.PrivateKey

	if err = ecdsaPrimaryKey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	if err := ecdsaPrimaryKey.Decrypt(password); err != nil {
		t.Fatal("Valid ECDSA key was marked as invalid: ", err)
	}

	if err = ecdsaPrimaryKey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	// Corrupt public X in primary key
	X := ecdsaPrimaryKey.PublicKey.PublicKey.(*ecdsa.PublicKey).X
	ecdsaPrimaryKey.PublicKey.PublicKey.(*ecdsa.PublicKey).X = new(big.Int).Add(X, big.NewInt(1))
	err = ecdsaPrimaryKey.Decrypt(password)
	if _, ok := err.(errors.KeyInvalidError); !ok {
		t.Fatal("Failed to detect invalid ECDSA key")
	}

	// ECDH
	ecdsaSubkey := ecdsaKey.Subkeys[0].PrivateKey
	if err = ecdsaSubkey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	if err := ecdsaSubkey.Decrypt(password); err != nil {
		t.Fatal("Valid ECDH key was marked as invalid: ", err)
	}

	if err = ecdsaSubkey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	// Corrupt public X in subkey
	ecdsaSubkey.PublicKey.PublicKey.(*ecdh.PublicKey).Point[5] ^= 1

	err = ecdsaSubkey.Decrypt(password)
	if _, ok := err.(errors.KeyInvalidError); !ok {
		t.Fatal("Failed to detect invalid ECDH key")
	}
}

func testKeyValidateEddsaOnDecrypt(t *testing.T, eddsaEntity *Entity, password []byte) {
	var err error

	eddsaPrimaryKey := eddsaEntity.PrivateKey // already encrypted
	if err = eddsaPrimaryKey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	if err := eddsaPrimaryKey.Decrypt(password); err != nil {
		t.Fatal("Valid EdDSA key was marked as invalid: ", err)
	}

	if err = eddsaPrimaryKey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	pubKey := *eddsaPrimaryKey.PublicKey.PublicKey.(*eddsa.PublicKey)
	pubKey.X[10] ^= 1
	err = eddsaPrimaryKey.Decrypt(password)
	if _, ok := err.(errors.KeyInvalidError); !ok {
		t.Fatal("Failed to detect invalid EdDSA key")
	}

	// ECDH
	ecdhSubkey := eddsaEntity.Subkeys[len(eddsaEntity.Subkeys)-1].PrivateKey
	if err = ecdhSubkey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	if err := ecdhSubkey.Decrypt(password); err != nil {
		t.Fatal("Valid ECDH key was marked as invalid: ", err)
	}

	if err = ecdhSubkey.Encrypt(password); err != nil {
		t.Fatal(err)
	}

	// Corrupt public X in subkey
	ecdhSubkey.PublicKey.PublicKey.(*ecdh.PublicKey).Point[5] ^= 1
	err = ecdhSubkey.Decrypt(password)
	if _, ok := err.(errors.KeyInvalidError); !ok {
		t.Fatal("Failed to detect invalid ECDH key")
	}
}

// ...the legacy bits
func testKeyValidateDsaElGamalOnDecrypt(t *testing.T, randomPassword []byte) {
	var err error

	dsaKeys, err := ReadArmoredKeyRing(bytes.NewBufferString(dsaPrivateKeyWithElGamalSubkey))
	if err != nil {
		t.Fatal(err)
	}
	dsaPrimaryKey := dsaKeys[0].PrivateKey // already encrypted
	if err := dsaPrimaryKey.Decrypt([]byte("password")); err != nil {
		t.Fatal("Valid DSA key was marked as invalid: ", err)
	}

	if err = dsaPrimaryKey.Encrypt(randomPassword); err != nil {
		t.Fatal(err)
	}
	// corrupt DSA generator
	G := dsaPrimaryKey.PublicKey.PublicKey.(*dsa.PublicKey).G
	dsaPrimaryKey.PublicKey.PublicKey.(*dsa.PublicKey).G = new(big.Int).Add(G, big.NewInt(1))
	err = dsaPrimaryKey.Decrypt(randomPassword)
	if _, ok := err.(errors.KeyInvalidError); !ok {
		t.Fatal("Failed to detect invalid DSA key")
	}

	// ElGamal
	elGamalSubkey := dsaKeys[0].Subkeys[0].PrivateKey // already encrypted
	if err := elGamalSubkey.Decrypt([]byte("password")); err != nil {
		t.Fatal("Valid ElGamal key was marked as invalid: ", err)
	}

	if err = elGamalSubkey.Encrypt(randomPassword); err != nil {
		t.Fatal(err)
	}

	// corrupt ElGamal generator
	G = elGamalSubkey.PublicKey.PublicKey.(*elgamal.PublicKey).G
	elGamalSubkey.PublicKey.PublicKey.(*elgamal.PublicKey).G = new(big.Int).Add(G, big.NewInt(1))
	err = elGamalSubkey.Decrypt(randomPassword)
	if _, ok := err.(errors.KeyInvalidError); !ok {
		t.Fatal("Failed to detect invalid ElGamal key")
	}
}

var foreignKeysv4 = []string{
	v4Key25519,
}

func TestReadPrivateForeignV4Key(t *testing.T) {
	for _, str := range foreignKeysv4 {
		kring, err := ReadArmoredKeyRing(strings.NewReader(str))
		if err != nil {
			t.Fatal(err)
		}
		checkV4Key(t, kring[0])
	}
}

func checkV4Key(t *testing.T, ent *Entity) {
	key := ent.PrimaryKey
	if key.Version != 4 {
		t.Errorf("wrong key version %d", key.Version)
	}
	if len(key.Fingerprint) != 20 {
		t.Errorf("Wrong fingerprint length: %d", len(key.Fingerprint))
	}
	signatures := ent.Revocations
	for _, id := range ent.Identities {
		signatures = append(signatures, id.SelfSignature)
		signatures = append(signatures, id.Signatures...)
	}
	for _, sig := range signatures {
		if sig == nil {
			continue
		}
		if sig.Version != 4 {
			t.Errorf("wrong signature version %d", sig.Version)
		}
		fgptLen := len(sig.IssuerFingerprint)
		if fgptLen != 20 {
			t.Errorf("Wrong fingerprint length in signature: %d", fgptLen)
		}
	}
}

// Should not panic (generated with go-fuzz)
func TestCorruptKeys(t *testing.T) {
	data := `-----BEGIN PGP PUBLIC KEY BLOCK00000

mQ00BF00000BCAD0000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000ABE000G0Dn000000000000000000iQ00BB0BAgAGBCG00000`
	ReadArmoredKeyRing(strings.NewReader(data))
}