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 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
|
package v2
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,
}
var allowAllAlgorithmsConfig = packet.Config{
RejectPublicKeyAlgorithms: map[packet.PublicKeyAlgorithm]bool{},
RejectCurves: map[packet.Curve]bool{},
RejectMessageHashAlgorithms: map[crypto.Hash]bool{},
MinRSABits: 512,
}
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, nil)
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, nil)
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, nil); 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, nil)
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, nil); ok {
t.Errorf("Expected no key at time %s, but got key %s", time2.Format(timeFormat), key.PublicKey.KeyIdShortString())
}
}
func TestReturnFirstUnexpiredSigningSubkey(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{
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()
expected := subkey2.PublicKey.KeyIdShortString()
subkey, found := entity.SigningKey(time1, nil)
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, nil)
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{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{entity}, message, &SignParams{
Config: &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{entity}, message, &SignParams{
Config: &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 = VerifyArmoredDetachedSignature(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 := VerifyArmoredDetachedSignature(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 = VerifyArmoredDetachedSignature(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, _ := ReadArmoredKeyRing(bytes.NewBufferString(missingCrossSignatureKey))
var config *packet.Config
_, err := keys[0].Subkeys[0].Verify(config.Now(), config)
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 = "no valid binding signature found for subkey"
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, _ := ReadArmoredKeyRing(bytes.NewBufferString(invalidCrossSignatureKey))
var config *packet.Config
_, err := keys[0].Subkeys[0].Verify(config.Now(), config)
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 = "no valid binding signature found for subkey"
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(nil, time.Now(), &packet.Config{}) {
t.Errorf("expected first identity not to be revoked")
}
if !secondIdentity.Revoked(nil, time.Now(), &packet.Config{}) {
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, nil); !found {
t.Errorf("Expected SigningKey to return a signing key when one User IDs is revoked")
}
if _, found := keys[0].EncryptionKey(time1, nil); !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(nil, time.Now(), &packet.Config{}) {
t.Errorf("expected first identity to be revoked")
}
if secondIdentity.Revoked(nil, time.Now(), &packet.Config{}) {
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, nil); !found {
t.Errorf("Expected SigningKey to return a signing key when first User IDs is revoked")
}
if _, found := keys[0].EncryptionKey(time1, nil); !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(nil, time.Now(), &packet.Config{}) {
t.Errorf("expected identity to be revoked")
}
if _, found := keys[0].SigningKey(time.Now(), nil); 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(), nil); 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.EncodeWithChecksumOption(&buf, PrivateKeyType, nil, false)
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))
}
}
signingkey, found := kring[0].SigningKey(time.Now(), nil)
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(), nil)
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.SelfCertifications), 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 len(subKey.Bindings) == 0 {
t.Fatalf("no binding subkey signature")
}
}
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))
}
if id == encryptionKey {
key, found := kring[0].EncryptionKey(time.Now(), &allowAllAlgorithmsConfig)
if !found || key.PublicKey.KeyId != id {
t.Errorf("Expected EncryptionKey to find key %X", id)
}
} else {
_, found := kring[0].SigningKeyById(time.Now(), id, &allowAllAlgorithmsConfig)
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))
}
signingkey, found := kring[0].SigningKeyById(time.Now(), revokedKey, nil)
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]
var zeroTime time.Time
var config *packet.Config
selfSig, err := subKey.LatestValidBindingSignature(zeroTime, config)
if err != nil {
t.Fatal("expected a self signature to be found")
}
if lifetime := selfSig.KeyLifetimeSecs; lifetime != nil {
t.Errorf("The signature has a key lifetime (%d), but it should be nil", *lifetime)
}
}
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 := allowAllAlgorithmsConfig
config.SigLifetimeSecs = 128
config.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.OtherCertifications {
if sig.Packet.IssuerKeyId == nil || *sig.Packet.IssuerKeyId != kring[1].PrimaryKey.KeyId {
continue
}
if err := kring[1].PrimaryKey.VerifyUserIdSignature(signedIdentity, kring[0].PrimaryKey, sig.Packet); err != nil {
t.Fatalf("error verifying new identity signature: %s", err)
}
if sig.Packet.SignerUserId == nil || *sig.Packet.SignerUserId != signerIdentity {
t.Fatalf("wrong or nil signer identity")
}
if sig.Packet.SigExpired(time.Now()) {
t.Fatalf("signature is expired")
}
if !sig.Packet.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,
Algorithm: packet.PubKeyAlgoEdDSA,
}
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 {
var zeroTime time.Time
selfSig, err := identity.LatestValidSelfCertification(zeroTime, c)
if err != nil {
t.Fatal("expected a self signature to be found ")
}
prefs := selfSig.PreferredHash
if len(prefs) == 0 {
t.Fatal("didn't find a preferred hash list in self signature")
}
ph := hashToHashId(c.DefaultHash)
if c.DefaultHash != crypto.SHA224 && 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 {
var zeroTime time.Time
selfSig, err := identity.LatestValidSelfCertification(zeroTime, &packet.Config{})
if err != nil {
t.Fatal("expected a self signature to be found ")
}
prefs := selfSig.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 {
var zeroTime time.Time
selfSig, err := identity.LatestValidSelfCertification(zeroTime, c)
if err != nil {
t.Fatal("expected a self signature to be found ")
}
prefs := selfSig.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 {
var zeroTime time.Time
selfSig, err := identity.LatestValidSelfCertification(zeroTime, &packet.Config{})
if err != nil {
t.Fatal("expected a self signature to be found ")
}
prefs := selfSig.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 {
var zeroTime time.Time
selfSig, err := identity.LatestValidSelfCertification(zeroTime, cfg)
if err != nil {
t.Fatal("expected a self signature to be found ")
}
if len(selfSig.PreferredCipherSuites) == 0 {
t.Fatal("didn't find a preferred mode in self signature")
}
cipher := selfSig.PreferredCipherSuites[0][0]
if cipher != uint8(cfg.Cipher()) {
t.Fatalf("Expected preferred cipher to be %d, got %d",
uint8(cfg.Cipher()),
selfSig.PreferredCipherSuites[0][0])
}
mode := selfSig.PreferredCipherSuites[0][1]
if mode != uint8(cfg.AEAD().DefaultMode) {
t.Fatalf("Expected preferred mode to be %d, got %d",
uint8(cfg.AEAD().DefaultMode),
selfSig.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) {
keySerializeConfig := &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, keySerializeConfig)
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.SelfCertifications), 1; numSigs != numExpected {
t.Fatalf("got %d signatures, expected %d", numSigs, numExpected)
}
notations := identity.SelfCertifications[0].Packet.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 {
var zeroTime time.Time
selfSig, err := sk.LatestValidSelfCertification(zeroTime, &packet.Config{})
if err != nil {
t.Fatal("expected a self signature to be found")
}
err = entity.PrimaryKey.VerifyUserIdSignature(sk.UserId.Id, entity.PrimaryKey, selfSig)
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 {
var zeroTime time.Time
var config *packet.Config
selfSig, err := sk.LatestValidBindingSignature(zeroTime, config)
if err != nil {
t.Fatal("expected a self signature to be found")
}
err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, selfSig)
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 {
var zeroTime time.Time
var config *packet.Config
selfSig, err := sk.LatestValidBindingSignature(zeroTime, config)
if err != nil {
t.Fatal("expected a self signature to be found")
}
err = entity.PrimaryKey.VerifyKeySignature(sk.PublicKey, selfSig)
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)
}
var zeroTime time.Time
var config *packet.Config
selfSig1, err := entity.Subkeys[1].LatestValidBindingSignature(zeroTime, config)
if err != nil {
t.Fatal("expected a self signature to be found")
}
if selfSig1.Hash != c.DefaultHash {
t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
selfSig1.Hash)
}
if selfSig1.EmbeddedSignature.Hash != c.DefaultHash {
t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
selfSig1.EmbeddedSignature.Hash)
}
err = entity.PrimaryKey.VerifyKeySignature(entity.Subkeys[1].PublicKey, selfSig1)
if err != nil {
t.Errorf("Invalid subkey signature: %v", err)
}
selfSig2, err := entity.Subkeys[2].LatestValidBindingSignature(zeroTime, config)
if err != nil {
t.Fatal("expected a self signature to be found")
}
if selfSig2.Hash != c.DefaultHash {
t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
selfSig2.Hash)
}
err = entity.PrimaryKey.VerifyKeySignature(entity.Subkeys[2].PublicKey, selfSig2)
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))
}
var zeroTime time.Time
var config *packet.Config
selfSig1, err := entity.Subkeys[1].LatestValidBindingSignature(zeroTime, config)
if err != nil {
t.Fatal("expected a self signature to be found")
}
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 selfSig1.Hash != c.DefaultHash {
t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
selfSig1.Hash)
}
if selfSig1.EmbeddedSignature.Hash != c.DefaultHash {
t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
selfSig1.EmbeddedSignature.Hash)
}
selfSig2, err := entity.Subkeys[2].LatestValidBindingSignature(zeroTime, config)
if err != nil {
t.Fatal("expected a self signature to be found")
}
if selfSig2.Hash != c.DefaultHash {
t.Fatalf("Expected subkey hash method: %v, got: %v", c.DefaultHash,
selfSig2.Hash)
}
err = entity.PrimaryKey.VerifyKeySignature(entity.Subkeys[1].PublicKey, selfSig1)
if err != nil {
t.Errorf("Invalid subkey signature: %v", err)
}
err = entity.PrimaryKey.VerifyKeySignature(entity.Subkeys[2].PublicKey, selfSig2)
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.Revoke(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.Packet)
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.Revoke(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].Packet.Hash != c.DefaultHash {
t.Fatalf("Expected signature hash method: %v, got: %v", c.DefaultHash,
entity.Revocations[0].Packet.Hash)
}
for _, r := range entity.Revocations {
err = entity.PrimaryKey.VerifyRevocationSignature(r.Packet)
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)
}
err = entity.Subkeys[0].Revoke(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(entity.Subkeys[0].Revocations))
}
revSig := entity.Subkeys[0].Revocations[0]
err = entity.PrimaryKey.VerifySubkeyRevocationSignature(revSig.Packet, entity.Subkeys[0].PublicKey)
if err != nil {
t.Fatal(err)
}
if revSig.Packet.RevocationReason == nil {
t.Fatal("Revocation reason was not set")
}
if revSig.Packet.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].Packet.RevocationReason == nil {
t.Fatal("Revocation reason lost after serialization of entity")
}
if newEntity.Subkeys[0].Revocations[0].Packet.RevocationReasonText == "" {
t.Fatal("Revocation reason text lost after serialization of 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.Bindings[0].Packet = &packet.Signature{Version: 4}
err = sk.Revoke(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 = sk.Revoke(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].Packet
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.SelfCertifications...)
}
for _, sig := range signatures {
if sig == nil {
continue
}
if sig.Packet.Version != 4 {
t.Errorf("wrong signature version %d", sig.Packet.Version)
}
fgptLen := len(sig.Packet.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))
}
func TestMultiIdentity(t *testing.T) {
data := `-----BEGIN PGP PUBLIC KEY BLOCK-----
xsDNBF2lnPIBDAC5cL9PQoQLTMuhjbYvb4Ncuuo0bfmgPRFywX53jPhoFf4Zg6mv
/seOXpgecTdOcVttfzC8ycIKrt3aQTiwOG/ctaR4Bk/t6ayNFfdUNxHWk4WCKzdz
/56fW2O0F23qIRd8UUJp5IIlN4RDdRCtdhVQIAuzvp2oVy/LaS2kxQoKvph/5pQ/
5whqsyroEWDJoSV0yOb25B/iwk/pLUFoyhDG9bj0kIzDxrEqW+7Ba8nocQlecMF3
X5KMN5kp2zraLv9d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BQSfZW2+LXoPZuVE/wGlQ01rh827KVZW4
lXvqsge+wtnWlszcselGATyzqOK9LdHPdZGzROZYI2e8c+paLNDdVPL6vdRBUnkC
aEkOtl1mr2JpQi5nTU+gTX4IeInC7E+1a9UDF/Y85ybUz8XV8rUnR76UqVC7KidN
epdHbZjjXCt8/Zo+Tec9JNbYNQB/e9ExmDntmlHEsSEQzFwzj8sxH48AEQEAAcLA
9gQYAQoAIBYhBNGmbhojsYLJmA94jPv8yCoBXnMwBQJdpZzyAhsMAAoJEPv8yCoB
XnMw6f8L/26C34dkjBffTzMj5Bdzm8MtF67OYneJ4TQMw7+41IL4rVcSKhIhk/3U
d5knaRtP2ef1+5F66h9/RPQOJ5+tvBwhBAcUWSupKnUrdVaZQanYmtSxcVV2PL9+
QEiNN3tzluhaWO//rACxJ+K/ZXQlIzwQVTpNhfGzAaMVV9zpf3u0k14itcv6alKY
8+rLZvO1wIIeRZLmU0tZDD5HtWDvUV7rIFI1WuoLb+KZgbYn3OWjCPHVdTrdZ2Cq
nZbG3SXw6awH9bzRLV9EXkbhIMez0deCVdeo+wFFklh8/5VK2b0vk/+wqMJxfpa1
lHvJLobzOP9fvrswsr92MA2+k901WeISR7qEzcI0Fdg8AyFAExaEK6VyjP7SXGLw
vfisw34OxuZr3qmx1Sufu4toH3XrB7QJN8XyqqbsGxUCBqWif9RSK4xjzRTe56iP
eiSJJOIciMP9i2ldI+KgLycyeDvGoBj0HCLO3gVaBe4ubVrj5KjhX2PVNEJd3XZR
zaXZE2aAMQ==
=Ty4h
-----END PGP PUBLIC KEY BLOCK-----`
key, err := ReadArmoredKeyRing(strings.NewReader(data))
if err != nil {
t.Fatal(err)
}
var config *packet.Config
sig, _ := key[0].PrimaryIdentity(config.Now(), &packet.Config{})
if err != nil {
t.Fatal(err)
}
if sig.IsPrimaryId == nil || !*sig.IsPrimaryId {
t.Fatal("expected primary identity to be selected")
}
}
func TestParseKeyWithUnsupportedSubkey(t *testing.T) {
data := `-----BEGIN PGP P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b6SELMyGkSvASD
Wp/uW6Q7if34b1eA7ptsZl+3hUib6w3O6DLyRXQHN4NW8fFMP0DR90MHBq4SZvQl
2NubY+bJOxAe2iOba5LKP3WJfldbGrcpcdYMltVIhBrs++zWqhEgDqNX7ihg+vbc
jxX5FogFMof99peG3ubW9t3tLdEO0J86ECNkyC8F+d+lYoEMUK2QzhpUDpwv/CGi
/2/1rgvVNvPhkTLVCT0OZ3HGwFs/x3eKCJVdblgE+Uqmfienbr0N6SfM25eteD8a
ZKc/M3D6Gg8lsEp/JrlEnPtaNj4MiyPvSFLl9K9/ObLnBxZgMZ9C/FJtNGnN7Mow
slAMmugzXY1twHa4iSDLk+Lu1WboxTc9Su/wbUfOVxp3ounB59RbXII0xwd3Vr+y
qfHgCWAXaeTB7d95+xIWoOPSUuT1cFba/Upegi5u5CV0E+g7knIhJg3eaHL1/dGK
ruxTPhR2zcmefHKGU7cCC/uo
=KLLX
-----END PGP PUBLIC KEY BLOCK-----`
_, err := ReadArmoredKeyRing(strings.NewReader(data))
if err != nil {
t.Fatal(err)
}
}
func TestParseUnsupportedSubkey(t *testing.T) {
data := `-----BEGIN PGP PUBLIC KEY BLOCK-----
xsDNBF2lnPIBDAC5cL9PQoQLTMuhjbYvb4Ncuuo0bfmgPRFywX53jPhoFf4Zg6mv
/seOXpgecTdOcVttfzC8ycIKrt3aQTiwOG/ctaR4Bk/t6ayNFfdUNxHWk4WCKzdz
/56fW2O0F23qIRd8UUJp5IIlN4RDdRCtdhVQIAuzvp2oVy/LaS2kxQoKvph/5pQ/
5whqsyroEWDJoSV0yOb25B/iwk/pLUFoyhDG9bj0kIzDxrEqW+7Ba8nocQlecMF3
X5KMN5kp2zraLv9dlBBpWW43XktjcCZgMy20SouraVma8Je/ECwUWYUiAZxLIlMv
9CurEOtxUw6N3RdOtLmYZS9uEnn5y1UkF88o8Nku890uk6BrewFzJyLAx5wRZ4F0
qV/yq36UWQ0JB/AUGhHVPdFf6pl6eaxBwT5GXvbBUibtf8YI2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z+GYgdvNSk51Wj
NciH07RTRuMS/aRhRg4OB8PQROmTnZ+iZS0=
=7DF0
-----END PGP PUBLIC KEY BLOCK-----
`
_, err := ReadArmoredKeyRing(strings.NewReader(data))
if err != nil {
t.Fatal(err)
}
}
func TestAllowAllKeyFlagsWhenMissing(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)
}
config := &packet.Config{}
primarySelfSignature, err := entity.VerifyPrimaryKey(time.Now(), config)
if err != nil {
t.Fatal(err)
}
if !entity.PrimaryKey.PubKeyAlgo.CanEncrypt() ||
!entity.PrimaryKey.PubKeyAlgo.CanSign() {
t.Fatal("PubKeyAlgo must be valid for signature and encryption")
}
/// Flags valid, but not set.
primarySelfSignature.FlagsValid = true
primarySelfSignature.FlagSign = false
primarySelfSignature.FlagCertify = false
primarySelfSignature.FlagEncryptCommunications = false
if isValidSigningKey(primarySelfSignature, entity.PrimaryKey.PubKeyAlgo, config) {
t.Error("isValidSigningKey must be false")
}
if isValidEncryptionKey(primarySelfSignature, entity.PrimaryKey.PubKeyAlgo, config) {
t.Error("isValidEncryptionKey must be false")
}
if isValidCertificationKey(primarySelfSignature, entity.PrimaryKey.PubKeyAlgo, config) {
t.Error("isValidCertificationKey must be false")
}
/// Flags not valid, but InsecureAllowAllKeyFlagsWhenMissing set.
primarySelfSignature.FlagsValid = false
config = &packet.Config{InsecureAllowAllKeyFlagsWhenMissing: true}
if !isValidSigningKey(primarySelfSignature, entity.PrimaryKey.PubKeyAlgo, config) {
t.Error("isValidSigningKey must be true when InsecureAllowAllKeyFlagsWhenMissing is true")
}
if !isValidEncryptionKey(primarySelfSignature, entity.PrimaryKey.PubKeyAlgo, config) {
t.Error("isValidEncryptionKey must be true when InsecureAllowAllKeyFlagsWhenMissing is true")
}
if !isValidCertificationKey(primarySelfSignature, entity.PrimaryKey.PubKeyAlgo, config) {
t.Error("isValidCertificationKey must be true when InsecureAllowAllKeyFlagsWhenMissing is true")
}
}
func TestEncryptionKeyError(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)
}
_, err = entity.EncryptionKeyWithError(time.Unix(1405544146, 0), nil)
if err == nil {
t.Fatal("should fail")
}
if !strings.Contains(err.Error(), "no valid self signature found") {
t.Fatal("wrong error")
}
entity.Subkeys[0].PublicKey.Version = 20
_, err = entity.EncryptionKeyWithError(time.Now(), nil)
if err == nil {
t.Fatal("should fail")
}
if !strings.Contains(err.Error(), "no valid binding signature found for subkey") {
t.Fatal("wrong error")
}
entity.Subkeys = nil
_, err = entity.EncryptionKeyWithError(time.Now(), nil)
if err == nil {
t.Fatal("should fail")
}
if !strings.Contains(err.Error(), "no encryption-capable key found (no key flags or invalid algorithm)") {
t.Fatal("wrong error")
}
}
|