DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (d1ed7de67f5a)

VCS Links

Line Code
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 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "lowkeyi.h"
#include "secasn1.h"
#include "secder.h"
#include "secoid.h"
#include "blapi.h"
#include "secitem.h"
#include "pcert.h"
#include "mcom_db.h"
#include "secerr.h"

#include "keydbi.h"
#include "lgdb.h"

/*
 * Record keys for keydb
 */
#define SALT_STRING "global-salt"
#define VERSION_STRING "Version"
#define KEYDB_PW_CHECK_STRING	"password-check"
#define KEYDB_PW_CHECK_LEN	14
#define KEYDB_FAKE_PW_CHECK_STRING	"fake-password-check"
#define KEYDB_FAKE_PW_CHECK_LEN	19

/* Size of the global salt for key database */
#define SALT_LENGTH     16

SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate)

const SEC_ASN1Template nsslowkey_EncryptedPrivateKeyInfoTemplate[] = {
    { SEC_ASN1_SEQUENCE,
	0, NULL, sizeof(NSSLOWKEYEncryptedPrivateKeyInfo) },
    { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
	offsetof(NSSLOWKEYEncryptedPrivateKeyInfo,algorithm),
	SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
    { SEC_ASN1_OCTET_STRING,
	offsetof(NSSLOWKEYEncryptedPrivateKeyInfo,encryptedData) },
    { 0 }
};

const SEC_ASN1Template nsslowkey_PointerToEncryptedPrivateKeyInfoTemplate[] = {
	{ SEC_ASN1_POINTER, 0, nsslowkey_EncryptedPrivateKeyInfoTemplate }
};


/* ====== Default key databse encryption algorithm ====== */
static void
sec_destroy_dbkey(NSSLOWKEYDBKey *dbkey)
{
    if ( dbkey && dbkey->arena ) {
	PORT_FreeArena(dbkey->arena, PR_FALSE);
    }
}

static void
free_dbt(DBT *dbt)
{
    if ( dbt ) {
	PORT_Free(dbt->data);
	PORT_Free(dbt);
    }
    
    return;
}

static int keydb_Get(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, 
		     unsigned int flags);
static int keydb_Put(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, 
		     unsigned int flags);
static int keydb_Sync(NSSLOWKEYDBHandle *db, unsigned int flags);
static int keydb_Del(NSSLOWKEYDBHandle *db, DBT *key, unsigned int flags);
static int keydb_Seq(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, 
		     unsigned int flags);
static void keydb_Close(NSSLOWKEYDBHandle *db);

/*
 * format of key database entries for version 3 of database:
 *	byte offset	field
 *	-----------	-----
 *	0		version
 *	1		salt-len
 *	2		nn-len
 *	3..		salt-data
 *	...		nickname
 *	...		encrypted-key-data
 */
static DBT *
encode_dbkey(NSSLOWKEYDBKey *dbkey,unsigned char version)
{
    DBT *bufitem = NULL;
    unsigned char *buf;
    int nnlen;
    char *nn;
    
    bufitem = (DBT *)PORT_ZAlloc(sizeof(DBT));
    if ( bufitem == NULL ) {
	goto loser;
    }
    
    if ( dbkey->nickname ) {
	nn = dbkey->nickname;
	nnlen = PORT_Strlen(nn) + 1;
    } else {
	nn = "";
	nnlen = 1;
    }
    
    /* compute the length of the record */
    /* 1 + 1 + 1 == version number header + salt length + nn len */
    bufitem->size = dbkey->salt.len + nnlen + dbkey->derPK.len + 1 + 1 + 1;
    
    bufitem->data = (void *)PORT_ZAlloc(bufitem->size);
    if ( bufitem->data == NULL ) {
	goto loser;
    }

    buf = (unsigned char *)bufitem->data;
    
    /* set version number */
    buf[0] = version;

    /* set length of salt */
    PORT_Assert(dbkey->salt.len < 256);
    buf[1] = dbkey->salt.len;

    /* set length of nickname */
    PORT_Assert(nnlen < 256);
    buf[2] = nnlen;

    /* copy salt */
    PORT_Memcpy(&buf[3], dbkey->salt.data, dbkey->salt.len);

    /* copy nickname */
    PORT_Memcpy(&buf[3 + dbkey->salt.len], nn, nnlen);

    /* copy encrypted key */
    PORT_Memcpy(&buf[3 + dbkey->salt.len + nnlen], dbkey->derPK.data,
	      dbkey->derPK.len);
    
    return(bufitem);
    
loser:
    if ( bufitem ) {
	free_dbt(bufitem);
    }
    
    return(NULL);
}

static NSSLOWKEYDBKey *
decode_dbkey(DBT *bufitem, int expectedVersion)
{
    NSSLOWKEYDBKey *dbkey;
    PLArenaPool *arena = NULL;
    unsigned char *buf;
    int version;
    int keyoff;
    int nnlen;
    int saltoff;
    
    buf = (unsigned char *)bufitem->data;

    version = buf[0];
    
    if ( version != expectedVersion ) {
	goto loser;
    }
    
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if ( arena == NULL ) {
	goto loser;
    }
    
    dbkey = (NSSLOWKEYDBKey *)PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYDBKey));
    if ( dbkey == NULL ) {
	goto loser;
    }

    dbkey->arena = arena;
    dbkey->salt.data = NULL;
    dbkey->derPK.data = NULL;
    
    dbkey->salt.len = buf[1];
    dbkey->salt.data = (unsigned char *)PORT_ArenaZAlloc(arena, dbkey->salt.len);
    if ( dbkey->salt.data == NULL ) {
	goto loser;
    }

    saltoff = 2;
    keyoff = 2 + dbkey->salt.len;
    
    if ( expectedVersion >= 3 ) {
	nnlen = buf[2];
	if ( nnlen ) {
	    dbkey->nickname = (char *)PORT_ArenaZAlloc(arena, nnlen + 1);
	    if ( dbkey->nickname ) {
		PORT_Memcpy(dbkey->nickname, &buf[keyoff+1], nnlen);
	    }
	}
	keyoff += ( nnlen + 1 );
	saltoff = 3;
    }

    PORT_Memcpy(dbkey->salt.data, &buf[saltoff], dbkey->salt.len);
    
    dbkey->derPK.len = bufitem->size - keyoff;
    dbkey->derPK.data = (unsigned char *)PORT_ArenaZAlloc(arena,dbkey->derPK.len);
    if ( dbkey->derPK.data == NULL ) {
	goto loser;
    }
    
    PORT_Memcpy(dbkey->derPK.data, &buf[keyoff], dbkey->derPK.len);
    
    return(dbkey);
    
loser:

    if ( arena ) {
	PORT_FreeArena(arena, PR_FALSE);
    }
    
    return(NULL);
}

static NSSLOWKEYDBKey *
get_dbkey(NSSLOWKEYDBHandle *handle, DBT *index)
{
    NSSLOWKEYDBKey *dbkey;
    DBT entry;
    int ret;
    
    /* get it from the database */
    ret = keydb_Get(handle, index, &entry, 0);
    if ( ret ) {
	PORT_SetError(SEC_ERROR_BAD_DATABASE);
	return NULL;
    }

    /* set up dbkey struct */

    dbkey = decode_dbkey(&entry, handle->version);

    return(dbkey);
}

static SECStatus
put_dbkey(NSSLOWKEYDBHandle *handle, DBT *index, NSSLOWKEYDBKey *dbkey, PRBool update)
{
    DBT *keydata = NULL;
    int status;
    
    keydata = encode_dbkey(dbkey, handle->version);
    if ( keydata == NULL ) {
	goto loser;
    }
    
    /* put it in the database */
    if ( update ) {
	status = keydb_Put(handle, index, keydata, 0);
    } else {
	status = keydb_Put(handle, index, keydata, R_NOOVERWRITE);
    }
    
    if ( status ) {
	goto loser;
    }

    /* sync the database */
    status = keydb_Sync(handle, 0);
    if ( status ) {
	goto loser;
    }

    free_dbt(keydata);
    return(SECSuccess);

loser:
    if ( keydata ) {
	free_dbt(keydata);
    }
    
    return(SECFailure);
}

SECStatus
nsslowkey_TraverseKeys(NSSLOWKEYDBHandle *handle, 
		 SECStatus (* keyfunc)(DBT *k, DBT *d, void *pdata),
		 void *udata )
{
    DBT data;
    DBT key;
    SECStatus status;
    int ret;

    if (handle == NULL) {
	return(SECFailure);
    }

    ret = keydb_Seq(handle, &key, &data, R_FIRST);
    if ( ret ) {
	return(SECFailure);
    }
    
    do {
	/* skip version record */
	if ( data.size > 1 ) {
	    if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) {
		if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) {
		    continue;
		}
	    }

	    /* skip password check */
	    if ( key.size == KEYDB_PW_CHECK_LEN ) {
		if ( PORT_Memcmp(key.data, KEYDB_PW_CHECK_STRING,
				 KEYDB_PW_CHECK_LEN) == 0 ) {
		    continue;
		}
	    }
	    
	    status = (* keyfunc)(&key, &data, udata);
	    if (status != SECSuccess) {
		return(status);
	    }
	}
    } while ( keydb_Seq(handle, &key, &data, R_NEXT) == 0 );

    return(SECSuccess);
}

#ifdef notdef
typedef struct keyNode {
    struct keyNode *next;
    DBT key;
} keyNode;

typedef struct {
    PLArenaPool *arena;
    keyNode *head;
} keyList;

static SECStatus
sec_add_key_to_list(DBT *key, DBT *data, void *arg)
{
    keyList *keylist;
    keyNode *node;
    void *keydata;
    
    keylist = (keyList *)arg;

    /* allocate the node struct */
    node = (keyNode*)PORT_ArenaZAlloc(keylist->arena, sizeof(keyNode));
    if ( node == NULL ) {
	return(SECFailure);
    }
    
    /* allocate room for key data */
    keydata = PORT_ArenaZAlloc(keylist->arena, key->size);
    if ( keydata == NULL ) {
	return(SECFailure);
    }

    /* link node into list */
    node->next = keylist->head;
    keylist->head = node;

    /* copy key into node */
    PORT_Memcpy(keydata, key->data, key->size);
    node->key.size = key->size;
    node->key.data = keydata;
    
    return(SECSuccess);
}
#endif

static SECItem *
decodeKeyDBGlobalSalt(DBT *saltData)
{
    SECItem *saltitem;
    
    saltitem = (SECItem *)PORT_ZAlloc(sizeof(SECItem));
    if ( saltitem == NULL ) {
	return(NULL);
    }
    
    saltitem->data = (unsigned char *)PORT_ZAlloc(saltData->size);
    if ( saltitem->data == NULL ) {
	PORT_Free(saltitem);
	return(NULL);
    }
    
    saltitem->len = saltData->size;
    PORT_Memcpy(saltitem->data, saltData->data, saltitem->len);
    
    return(saltitem);
}

static SECItem *
GetKeyDBGlobalSalt(NSSLOWKEYDBHandle *handle)
{
    DBT saltKey;
    DBT saltData;
    int ret;
    
    saltKey.data = SALT_STRING;
    saltKey.size = sizeof(SALT_STRING) - 1;

    ret = keydb_Get(handle, &saltKey, &saltData, 0);
    if ( ret ) {
	return(NULL);
    }

    return(decodeKeyDBGlobalSalt(&saltData));
}

static SECStatus
StoreKeyDBGlobalSalt(NSSLOWKEYDBHandle *handle, SECItem *salt)
{
    DBT saltKey;
    DBT saltData;
    int status;
    
    saltKey.data = SALT_STRING;
    saltKey.size = sizeof(SALT_STRING) - 1;

    saltData.data = (void *)salt->data;
    saltData.size = salt->len;

    /* put global salt into the database now */
    status = keydb_Put(handle, &saltKey, &saltData, 0);
    if ( status ) {
	return(SECFailure);
    }

    return(SECSuccess);
}

static SECStatus
makeGlobalVersion(NSSLOWKEYDBHandle *handle)
{
    unsigned char version;
    DBT versionData;
    DBT versionKey;
    int status;
    
    version = NSSLOWKEY_DB_FILE_VERSION;
    versionData.data = &version;
    versionData.size = 1;
    versionKey.data = VERSION_STRING;
    versionKey.size = sizeof(VERSION_STRING)-1;
		
    /* put version string into the database now */
    status = keydb_Put(handle, &versionKey, &versionData, 0);
    if ( status ) {
	return(SECFailure);
    }
    handle->version = version;

    return(SECSuccess);
}


static SECStatus
makeGlobalSalt(NSSLOWKEYDBHandle *handle)
{
    DBT saltKey;
    DBT saltData;
    unsigned char saltbuf[16];
    int status;
    
    saltKey.data = SALT_STRING;
    saltKey.size = sizeof(SALT_STRING) - 1;

    saltData.data = (void *)saltbuf;
    saltData.size = sizeof(saltbuf);
    RNG_GenerateGlobalRandomBytes(saltbuf, sizeof(saltbuf));

    /* put global salt into the database now */
    status = keydb_Put(handle, &saltKey, &saltData, 0);
    if ( status ) {
	return(SECFailure);
    }

    return(SECSuccess);
}

static SECStatus
encodePWCheckEntry(PLArenaPool *arena, SECItem *entry, SECOidTag alg,
		   SECItem *encCheck);

static unsigned char
nsslowkey_version(NSSLOWKEYDBHandle *handle)
{
    DBT versionKey;
    DBT versionData;
    int ret;
    versionKey.data = VERSION_STRING;
    versionKey.size = sizeof(VERSION_STRING)-1;

    if (handle->db == NULL) {
	return 255;
    }

    /* lookup version string in database */
    ret = keydb_Get( handle, &versionKey, &versionData, 0 );

    /* error accessing the database */
    if ( ret < 0 ) {
	return 255;
    }

    if ( ret >= 1 ) {
	return 0;
    }
    return *( (unsigned char *)versionData.data);
}

static PRBool
seckey_HasAServerKey(NSSLOWKEYDBHandle *handle)
{
    DBT key;
    DBT data;
    int ret;
    PRBool found = PR_FALSE;

    ret = keydb_Seq(handle, &key, &data, R_FIRST);
    if ( ret ) {
	return PR_FALSE;
    }
    
    do {
	/* skip version record */
	if ( data.size > 1 ) {
	    /* skip salt */
	    if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) {
		if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) {
		    continue;
		}
	    }
	    /* skip pw check entry */
	    if ( key.size == KEYDB_PW_CHECK_LEN ) {
		if ( PORT_Memcmp(key.data, KEYDB_PW_CHECK_STRING, 
						KEYDB_PW_CHECK_LEN) == 0 ) {
		    continue;
		}
	    }

	    /* keys stored by nickname will have 0 as the last byte of the
	     * db key.  Other keys must be stored by modulus.  We will not
	     * update those because they are left over from a keygen that
	     * never resulted in a cert.
	     */
	    if ( ((unsigned char *)key.data)[key.size-1] != 0 ) {
		continue;
	    }

	    if (PORT_Strcmp(key.data,"Server-Key") == 0) {
		found = PR_TRUE;
	        break;
	    }
	    
	}
    } while ( keydb_Seq(handle, &key, &data, R_NEXT) == 0 );

    return found;
}

/* forward declare local create function */
static NSSLOWKEYDBHandle * nsslowkey_NewHandle(DB *dbHandle);

/*
 * currently updates key database from v2 to v3
 */
static SECStatus
nsslowkey_UpdateKeyDBPass1(NSSLOWKEYDBHandle *handle)
{
    SECStatus rv;
    DBT checkKey;
    DBT checkData;
    DBT saltKey;
    DBT saltData;
    DBT key;
    DBT data;
    unsigned char version;
    NSSLOWKEYDBKey *dbkey = NULL;
    NSSLOWKEYDBHandle *update = NULL;
    SECItem *oldSalt = NULL;
    int ret;
    SECItem checkitem;

    if ( handle->updatedb == NULL ) {
	return SECSuccess;
    }

    /* create a full DB Handle for our update so we 
     * can use the correct locks for the db primatives */
    update = nsslowkey_NewHandle(handle->updatedb);
    if ( update == NULL) {
	return SECSuccess;
    }

    /* update has now inherited the database handle */
    handle->updatedb = NULL;

    /*
     * check the version record
     */
    version = nsslowkey_version(update);
    if (version != 2) {
	goto done;
    }

    saltKey.data = SALT_STRING;
    saltKey.size = sizeof(SALT_STRING) - 1;

    ret = keydb_Get(update, &saltKey, &saltData, 0);
    if ( ret ) {
	/* no salt in old db, so it is corrupted */
	goto done;
    }

    oldSalt = decodeKeyDBGlobalSalt(&saltData);
    if ( oldSalt == NULL ) {
	/* bad salt in old db, so it is corrupted */
	goto done;
    }

    /*
     * look for a pw check entry
     */
    checkKey.data = KEYDB_PW_CHECK_STRING;
    checkKey.size = KEYDB_PW_CHECK_LEN;
    
    ret = keydb_Get(update, &checkKey, &checkData, 0 );
    if (ret) {
	/*
	 * if we have a key, but no KEYDB_PW_CHECK_STRING, then this must
	 * be an old server database, and it does have a password associated
	 * with it. Put a fake entry in so we can identify this db when we do
	 * get the password for it.
	 */
	if (seckey_HasAServerKey(update)) {
	    DBT fcheckKey;
	    DBT fcheckData;

	    /*
	     * include a fake string
	     */
	    fcheckKey.data = KEYDB_FAKE_PW_CHECK_STRING;
	    fcheckKey.size = KEYDB_FAKE_PW_CHECK_LEN;
	    fcheckData.data = "1";
	    fcheckData.size = 1;
	    /* put global salt into the new database now */
	    ret = keydb_Put( handle, &saltKey, &saltData, 0);
	    if ( ret ) {
		goto done;
	    }
	    ret = keydb_Put( handle, &fcheckKey, &fcheckData, 0);
	    if ( ret ) {
		goto done;
	    }
	} else {
	    goto done;
	}
    } else {
	/* put global salt into the new database now */
	ret = keydb_Put( handle, &saltKey, &saltData, 0);
	if ( ret ) {
	    goto done;
	}

	dbkey = decode_dbkey(&checkData, 2);
	if ( dbkey == NULL ) {
	    goto done;
	}
	checkitem = dbkey->derPK;
	dbkey->derPK.data = NULL;
    
	/* format the new pw check entry */
	rv = encodePWCheckEntry(NULL, &dbkey->derPK, SEC_OID_RC4, &checkitem);
	if ( rv != SECSuccess ) {
	    goto done;
	}

	rv = put_dbkey(handle, &checkKey, dbkey, PR_TRUE);
	if ( rv != SECSuccess ) {
	    goto done;
	}

	/* free the dbkey */
	sec_destroy_dbkey(dbkey);
	dbkey = NULL;
    }
    
    
    /* now traverse the database */
    ret = keydb_Seq(update, &key, &data, R_FIRST);
    if ( ret ) {
	goto done;
    }
    
    do {
	/* skip version record */
	if ( data.size > 1 ) {
	    /* skip salt */
	    if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) {
		if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) {
		    continue;
		}
	    }
	    /* skip pw check entry */
	    if ( key.size == checkKey.size ) {
		if ( PORT_Memcmp(key.data, checkKey.data, key.size) == 0 ) {
		    continue;
		}
	    }

	    /* keys stored by nickname will have 0 as the last byte of the
	     * db key.  Other keys must be stored by modulus.  We will not
	     * update those because they are left over from a keygen that
	     * never resulted in a cert.
	     */
	    if ( ((unsigned char *)key.data)[key.size-1] != 0 ) {
		continue;
	    }
	    
	    dbkey = decode_dbkey(&data, 2);
	    if ( dbkey == NULL ) {
		continue;
	    }

	    /* This puts the key into the new database with the same
	     * index (nickname) that it had before.  The second pass
	     * of the update will have the password.  It will decrypt
	     * and re-encrypt the entries using a new algorithm.
	     */
	    dbkey->nickname = (char *)key.data;
	    rv = put_dbkey(handle, &key, dbkey, PR_FALSE);
	    dbkey->nickname = NULL;

	    sec_destroy_dbkey(dbkey);
	}
    } while ( keydb_Seq(update, &key, &data, R_NEXT) == 0 );

    dbkey = NULL;

done:
    /* sync the database */
    ret = keydb_Sync(handle, 0);

    nsslowkey_CloseKeyDB(update);
    
    if ( oldSalt ) {
	SECITEM_FreeItem(oldSalt, PR_TRUE);
    }
    
    if ( dbkey ) {
	sec_destroy_dbkey(dbkey);
    }

    return(SECSuccess);
}

static SECStatus
openNewDB(const char *appName, const char *prefix, const char *dbname, 
	NSSLOWKEYDBHandle *handle, NSSLOWKEYDBNameFunc namecb, void *cbarg)
{
    SECStatus rv = SECFailure;
    int status = RDB_FAIL;
    char *updname = NULL;
    DB *updatedb = NULL;
    PRBool updated = PR_FALSE;
    int ret;

    if (appName) {
	handle->db = rdbopen( appName, prefix, "key", NO_CREATE, &status);
    } else {
	handle->db = dbopen( dbname, NO_CREATE, 0600, DB_HASH, 0 );
    }
    /* if create fails then we lose */
    if ( handle->db == NULL ) {
	return (status == RDB_RETRY) ? SECWouldBlock: SECFailure;
    }

    /* force a transactional read, which will verify that one and only one
     * process attempts the update. */
    if (nsslowkey_version(handle) == NSSLOWKEY_DB_FILE_VERSION) {
	/* someone else has already updated the database for us */
	db_InitComplete(handle->db);
	return SECSuccess;
    }

    /*
     * if we are creating a multiaccess database, see if there is a
     * local database we can update from.
     */
    if (appName) {
        NSSLOWKEYDBHandle *updateHandle;
	updatedb = dbopen( dbname, NO_RDONLY, 0600, DB_HASH, 0 );
	if (!updatedb) {
	    goto noupdate;
	}

	/* nsslowkey_version needs a full handle because it calls
         * the kdb_Get() function, which needs to lock.
         */
        updateHandle = nsslowkey_NewHandle(updatedb);
	if (!updateHandle) {
	    updatedb->close(updatedb);
	    goto noupdate;
	}

	handle->version = nsslowkey_version(updateHandle);
	if (handle->version != NSSLOWKEY_DB_FILE_VERSION) {
	    nsslowkey_CloseKeyDB(updateHandle);
	    goto noupdate;
	}

	/* copy the new DB from the old one */
	db_Copy(handle->db, updatedb);
	nsslowkey_CloseKeyDB(updateHandle);
	db_InitComplete(handle->db);
	return SECSuccess;
    }
noupdate:

    /* update the version number */
    rv = makeGlobalVersion(handle);
    if ( rv != SECSuccess ) {
	goto loser;
    }

    /*
     * try to update from v2 db
     */
    updname = (*namecb)(cbarg, 2);
    if ( updname != NULL ) {
	handle->updatedb = dbopen( updname, NO_RDONLY, 0600, DB_HASH, 0 );
        PORT_Free( updname );

	if ( handle->updatedb ) {
	    /*
	     * Try to update the db using a null password.  If the db
	     * doesn't have a password, then this will work.  If it does
	     * have a password, then this will fail and we will do the
	     * update later
	     */
	    rv = nsslowkey_UpdateKeyDBPass1(handle);
	    if ( rv == SECSuccess ) {
		updated = PR_TRUE;
	    }
	}
	    
    }

    /* we are using the old salt if we updated from an old db */
    if ( ! updated ) {
	rv = makeGlobalSalt(handle);
	if ( rv != SECSuccess ) {
	   goto loser;
	}
    }
	
    /* sync the database */
    ret = keydb_Sync(handle, 0);
    if ( ret ) {
	rv = SECFailure;
	goto loser;
    }
    rv = SECSuccess;

loser:
    db_InitComplete(handle->db);
    return rv;
}


static DB *
openOldDB(const char *appName, const char *prefix, const char *dbname, 
					PRBool openflags) {
    DB *db = NULL;

    if (appName) {
	db = rdbopen( appName, prefix, "key", openflags, NULL);
    } else {
	db = dbopen( dbname, openflags, 0600, DB_HASH, 0 );
    }

    return db;
}

/* check for correct version number */
static PRBool
verifyVersion(NSSLOWKEYDBHandle *handle)
{
    int version = nsslowkey_version(handle);

    handle->version = version;
    if (version != NSSLOWKEY_DB_FILE_VERSION ) {
	if (handle->db) {
	    keydb_Close(handle);
	    handle->db = NULL;
	}
    }
    return handle->db != NULL;
}

static NSSLOWKEYDBHandle *
nsslowkey_NewHandle(DB *dbHandle)
{
    NSSLOWKEYDBHandle *handle;
    handle = (NSSLOWKEYDBHandle *)PORT_ZAlloc (sizeof(NSSLOWKEYDBHandle));
    if (handle == NULL) {
	PORT_SetError (SEC_ERROR_NO_MEMORY);
	return NULL;
    }

    handle->appname = NULL;
    handle->dbname = NULL;
    handle->global_salt = NULL;
    handle->updatedb = NULL;
    handle->db = dbHandle;
    handle->ref = 1;
    handle->lock = PZ_NewLock(nssILockKeyDB);

    return handle;
}

NSSLOWKEYDBHandle *
nsslowkey_OpenKeyDB(PRBool readOnly, const char *appName, const char *prefix,
				NSSLOWKEYDBNameFunc namecb, void *cbarg)
{
    NSSLOWKEYDBHandle *handle = NULL;
    SECStatus rv;
    int openflags;
    char *dbname = NULL;


    handle = nsslowkey_NewHandle(NULL);

    openflags = readOnly ? NO_RDONLY : NO_RDWR;


    dbname = (*namecb)(cbarg, NSSLOWKEY_DB_FILE_VERSION);
    if ( dbname == NULL ) {
	goto loser;
    }
    handle->appname = appName ? PORT_Strdup(appName) : NULL ;
    handle->dbname = (appName == NULL) ? PORT_Strdup(dbname) : 
			(prefix ? PORT_Strdup(prefix) : NULL);
    handle->readOnly = readOnly;



    handle->db = openOldDB(appName, prefix, dbname, openflags);
    if (handle->db) {
	verifyVersion(handle);
	if (handle->version == 255) {
	    goto loser;
	}
    }

    /* if first open fails, try to create a new DB */
    if ( handle->db == NULL ) {
	if ( readOnly ) {
	    goto loser;
	}

	rv = openNewDB(appName, prefix, dbname, handle, namecb, cbarg);
	/* two processes started to initialize the database at the same time.
	 * The multiprocess code blocked the second one, then had it retry to
	 * see if it can just open the database normally */
	if (rv == SECWouldBlock) {
	    handle->db = openOldDB(appName,prefix,dbname, openflags);
	    verifyVersion(handle);
	    if (handle->db == NULL) {
		goto loser;
	    }
	} else if (rv != SECSuccess) {
	    goto loser;
	}
    }

    handle->global_salt = GetKeyDBGlobalSalt(handle);
    if ( dbname )
        PORT_Free( dbname );
    return handle;

loser:

    if ( dbname )
        PORT_Free( dbname );
    PORT_SetError(SEC_ERROR_BAD_DATABASE);
    nsslowkey_CloseKeyDB(handle);
    return NULL;
}

/*
 * Close the database
 */
void
nsslowkey_CloseKeyDB(NSSLOWKEYDBHandle *handle)
{
    if (handle != NULL) {
	if (handle->db != NULL) {
	    keydb_Close(handle);
	}
	if (handle->updatedb) {
	    handle->updatedb->close(handle->updatedb);
        }
	if (handle->dbname) PORT_Free(handle->dbname);
	if (handle->appname) PORT_Free(handle->appname);
	if (handle->global_salt) {
	    SECITEM_FreeItem(handle->global_salt,PR_TRUE);
	}
	if (handle->lock != NULL) {
	    SKIP_AFTER_FORK(PZ_DestroyLock(handle->lock));
	}
	    
	PORT_Free(handle);
    }
}

/* Get the key database version */
int
nsslowkey_GetKeyDBVersion(NSSLOWKEYDBHandle *handle)
{
    PORT_Assert(handle != NULL);

    return handle->version;
}

/*
 * Delete a private key that was stored in the database
 */
SECStatus
nsslowkey_DeleteKey(NSSLOWKEYDBHandle *handle, const SECItem *pubkey)
{
    DBT namekey;
    int ret;

    if (handle == NULL) {
	PORT_SetError(SEC_ERROR_BAD_DATABASE);
	return(SECFailure);
    }

    /* set up db key and data */
    namekey.data = pubkey->data;
    namekey.size = pubkey->len;

    /* delete it from the database */
    ret = keydb_Del(handle, &namekey, 0);
    if ( ret ) {
	PORT_SetError(SEC_ERROR_BAD_DATABASE);
	return(SECFailure);
    }

    /* sync the database */
    ret = keydb_Sync(handle, 0);
    if ( ret ) {
	PORT_SetError(SEC_ERROR_BAD_DATABASE);
	return(SECFailure);
    }

    return(SECSuccess);
}

/*
 * Store a key in the database, indexed by its public key modulus.(value!)
 */
SECStatus
nsslowkey_StoreKeyByPublicKey(NSSLOWKEYDBHandle *handle, 
			   NSSLOWKEYPrivateKey *privkey,
			   SECItem *pubKeyData,
			   char *nickname,
			   SDB *sdb)
{
    return nsslowkey_StoreKeyByPublicKeyAlg(handle, privkey, pubKeyData, 
	     nickname, sdb, PR_FALSE);
}

SECStatus
nsslowkey_UpdateNickname(NSSLOWKEYDBHandle *handle, 
			   NSSLOWKEYPrivateKey *privkey,
			   SECItem *pubKeyData,
			   char *nickname,
			   SDB *sdb)
{
    return nsslowkey_StoreKeyByPublicKeyAlg(handle, privkey, pubKeyData, 
	     nickname, sdb, PR_TRUE);
}

/* see if the symetric CKA_ID already Exists.
 */
PRBool
nsslowkey_KeyForIDExists(NSSLOWKEYDBHandle *handle, SECItem *id)
{
    DBT namekey;
    DBT dummy;
    int status;

    namekey.data = (char *)id->data;
    namekey.size = id->len;
    status = keydb_Get(handle, &namekey, &dummy, 0);
    if ( status ) {
	return PR_FALSE;
    }
    
    return PR_TRUE;
}

/* see if the public key for this cert is in the database filed
 * by modulus
 */
PRBool
nsslowkey_KeyForCertExists(NSSLOWKEYDBHandle *handle, NSSLOWCERTCertificate *cert)
{
    NSSLOWKEYPublicKey *pubkey = NULL;
    DBT namekey;
    DBT dummy;
    int status;
    
    /* get cert's public key */
    pubkey = nsslowcert_ExtractPublicKey(cert);
    if ( pubkey == NULL ) {
	return PR_FALSE;
    }

    /* TNH - make key from NSSLOWKEYPublicKey */
    switch (pubkey->keyType) {
      case NSSLOWKEYRSAKey:
	namekey.data = pubkey->u.rsa.modulus.data;
	namekey.size = pubkey->u.rsa.modulus.len;
	break;
      case NSSLOWKEYDSAKey:
	namekey.data = pubkey->u.dsa.publicValue.data;
	namekey.size = pubkey->u.dsa.publicValue.len;
	break;
      case NSSLOWKEYDHKey:
	namekey.data = pubkey->u.dh.publicValue.data;
	namekey.size = pubkey->u.dh.publicValue.len;
	break;
#ifndef NSS_DISABLE_ECC
      case NSSLOWKEYECKey:
	namekey.data = pubkey->u.ec.publicValue.data;
	namekey.size = pubkey->u.ec.publicValue.len;
	break;
#endif /* NSS_DISABLE_ECC */
      default:
	/* XXX We don't do Fortezza or DH yet. */
	return PR_FALSE;
    }

    if (handle->version != 3) {
	unsigned char buf[SHA1_LENGTH];
	SHA1_HashBuf(buf,namekey.data,namekey.size);
	/* NOTE: don't use pubkey after this! it's now thrashed */
	PORT_Memcpy(namekey.data,buf,sizeof(buf));
	namekey.size = sizeof(buf);
    }

    status = keydb_Get(handle, &namekey, &dummy, 0);
    /* some databases have the key stored as a signed value */
    if (status) {
	unsigned char *buf = (unsigned char *)PORT_Alloc(namekey.size+1);
	if (buf) {
	    PORT_Memcpy(&buf[1], namekey.data, namekey.size);
	    buf[0] = 0;
	    namekey.data = buf;
	    namekey.size ++;
    	    status = keydb_Get(handle, &namekey, &dummy, 0);
	    PORT_Free(buf);
	}
    }
    lg_nsslowkey_DestroyPublicKey(pubkey);
    if ( status ) {
	return PR_FALSE;
    }
    
    return PR_TRUE;
}

typedef struct NSSLowPasswordDataParamStr {
    SECItem salt;
    SECItem iter;
} NSSLowPasswordDataParam;

static const SEC_ASN1Template NSSLOWPasswordParamTemplate[] =
{
    {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLowPasswordDataParam) },
    {SEC_ASN1_OCTET_STRING, offsetof(NSSLowPasswordDataParam, salt) },
    {SEC_ASN1_INTEGER, offsetof(NSSLowPasswordDataParam, iter) },
    {0}
};
struct LGEncryptedDataInfoStr {
    SECAlgorithmID algorithm;
    SECItem encryptedData;
};
typedef struct LGEncryptedDataInfoStr LGEncryptedDataInfo;

const SEC_ASN1Template lg_EncryptedDataInfoTemplate[] = {
    { SEC_ASN1_SEQUENCE,
        0, NULL, sizeof(LGEncryptedDataInfo) },
    { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
        offsetof(LGEncryptedDataInfo,algorithm),
        SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
    { SEC_ASN1_OCTET_STRING,
        offsetof(LGEncryptedDataInfo,encryptedData) },
    { 0 }
};

static SECItem *
nsslowkey_EncodePW(SECOidTag alg, const SECItem *salt, SECItem *data)
{
    NSSLowPasswordDataParam param;
    LGEncryptedDataInfo edi;
    PLArenaPool *arena;
    unsigned char one = 1;
    SECItem *epw = NULL;
    SECItem *encParam;
    SECStatus rv;

    param.salt = *salt;
    param.iter.type = siBuffer;  /* encode as signed integer */
    param.iter.data = &one;
    param.iter.len = 1;
    edi.encryptedData = *data;

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	return NULL;
    }

    encParam = SEC_ASN1EncodeItem(arena, NULL, &param,
				  NSSLOWPasswordParamTemplate);
    if (encParam == NULL) {
	goto loser;
    }
    rv = SECOID_SetAlgorithmID(arena, &edi.algorithm, alg, encParam);
    if (rv != SECSuccess) {
	goto loser;
    }
    epw = SEC_ASN1EncodeItem(NULL, NULL, &edi, lg_EncryptedDataInfoTemplate);

loser:
    PORT_FreeArena(arena, PR_FALSE);
    return epw;
}

static SECItem *
nsslowkey_DecodePW(const SECItem *derData, SECOidTag *alg, SECItem *salt)
{
    NSSLowPasswordDataParam param;
    LGEncryptedDataInfo edi;
    PLArenaPool *arena;
    SECItem *pwe = NULL;
    SECStatus rv;

    salt->data = NULL;
    param.iter.type = siBuffer;  /* decode as signed integer */

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	return NULL;
    }

    rv = SEC_QuickDERDecodeItem(arena, &edi, lg_EncryptedDataInfoTemplate, 
						derData);
    if (rv != SECSuccess) {
	goto loser;
    }
    *alg = SECOID_GetAlgorithmTag(&edi.algorithm);
    rv = SEC_QuickDERDecodeItem(arena, &param, NSSLOWPasswordParamTemplate,
						&edi.algorithm.parameters);
    if (rv != SECSuccess) {
	goto loser;
    }
    rv = SECITEM_CopyItem(NULL, salt, &param.salt);
    if (rv != SECSuccess) {
	goto loser;
    }
    pwe = SECITEM_DupItem(&edi.encryptedData);

loser:
    if (!pwe && salt->data) {
	PORT_Free(salt->data);
	salt->data = NULL;
    }
    PORT_FreeArena(arena, PR_FALSE);
    return pwe;
}


/*
 * check to see if the user has a password
 */
static SECStatus
nsslowkey_GetPWCheckEntry(NSSLOWKEYDBHandle *handle,NSSLOWKEYPasswordEntry *entry)
{
    DBT checkkey; /*, checkdata; */
    NSSLOWKEYDBKey *dbkey = NULL;
    SECItem   *global_salt = NULL; 
    SECItem   *item = NULL; 
    SECItem   entryData, oid;
    SECItem   none = { siBuffer, NULL, 0 };
    SECStatus rv = SECFailure;
    SECOidTag algorithm;

    if (handle == NULL) {
	/* PORT_SetError */
	return(SECFailure);
    }

    global_salt = GetKeyDBGlobalSalt(handle);
    if (!global_salt) {
	global_salt = &none;
    }
    if (global_salt->len > sizeof(entry->data)) {
	/* PORT_SetError */
	goto loser;
    }
	
    PORT_Memcpy(entry->data, global_salt->data, global_salt->len);
    entry->salt.data = entry->data;
    entry->salt.len = global_salt->len;
    entry->value.data = &entry->data[entry->salt.len];

    checkkey.data = KEYDB_PW_CHECK_STRING;
    checkkey.size = KEYDB_PW_CHECK_LEN;
    dbkey = get_dbkey(handle, &checkkey);
    if (dbkey == NULL) {
	/* handle 'FAKE' check here */
	goto loser;
    }

    oid.len = dbkey->derPK.data[0];
    oid.data = &dbkey->derPK.data[1];

    if (dbkey->derPK.len < (KEYDB_PW_CHECK_LEN + 1 +oid.len)) {
	goto loser;
    }
    algorithm = SECOID_FindOIDTag(&oid);
    entryData.type = siBuffer;
    entryData.len = dbkey->derPK.len - (oid.len+1);
    entryData.data = &dbkey->derPK.data[oid.len+1];

    item = nsslowkey_EncodePW(algorithm, &dbkey->salt, &entryData);
    if (!item || (item->len + entry->salt.len) > sizeof(entry->data)) {
	goto loser;
    }
    PORT_Memcpy(entry->value.data, item->data, item->len);
    entry->value.len = item->len;
    rv = SECSuccess;

loser:
    if (item) {
	SECITEM_FreeItem(item, PR_TRUE);
    }
    if (dbkey) {
 	sec_destroy_dbkey(dbkey);
    }
    if (global_salt != &none) {
	SECITEM_FreeItem(global_salt,PR_TRUE);
    }
    return rv;
}

/*
 * check to see if the user has a password
 */
static SECStatus
nsslowkey_PutPWCheckEntry(NSSLOWKEYDBHandle *handle,NSSLOWKEYPasswordEntry *entry)
{
    DBT checkkey;
    NSSLOWKEYDBKey *dbkey = NULL;
    SECItem   *item = NULL; 
    SECItem   salt; 
    SECOidTag algid;
    SECStatus rv = SECFailure;
    PLArenaPool *arena;
    int ret;

    if (handle == NULL) {
	/* PORT_SetError */
	return(SECFailure);
    }

    checkkey.data = KEYDB_PW_CHECK_STRING;
    checkkey.size = KEYDB_PW_CHECK_LEN;

    salt.data = NULL;
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	return SECFailure;
    }

    item = nsslowkey_DecodePW(&entry->value, &algid, &salt);
    if (item == NULL) {
	goto loser;
    }

    dbkey = PORT_ArenaZNew(arena, NSSLOWKEYDBKey);
    if (dbkey == NULL) {
	goto loser;
    }

    dbkey->arena = arena;

    rv = SECITEM_CopyItem(arena, &dbkey->salt, &salt);
    if (rv != SECSuccess) {
	goto loser;
    }

    rv = encodePWCheckEntry(arena, &dbkey->derPK, algid, item);
    if (rv != SECSuccess) {
	goto loser;
    }

    rv = put_dbkey(handle, &checkkey, dbkey, PR_TRUE);
    if (rv != SECSuccess) {
	goto loser;
    }

    if (handle->global_salt) {
	SECITEM_FreeItem(handle->global_salt, PR_TRUE);
	handle->global_salt = NULL;
    }
    rv = StoreKeyDBGlobalSalt(handle, &entry->salt);
    if (rv != SECSuccess) {
	goto loser;
    }
    ret = keydb_Sync(handle, 0);
    if ( ret ) {
	rv = SECFailure;
	goto loser;
    }
    handle->global_salt = GetKeyDBGlobalSalt(handle);

loser:
    if (item) {
	SECITEM_FreeItem(item, PR_TRUE);
    }
    if (arena) {
	PORT_FreeArena(arena, PR_TRUE);
    }
    if (salt.data) {
	PORT_Free(salt.data);
    }
    return rv;
}

#ifdef EC_DEBUG
#define SEC_PRINT(str1, str2, num, sitem) \
    printf("pkcs11c.c:%s:%s (keytype=%d) [len=%d]\n", \
            str1, str2, num, sitem->len); \
    for (i = 0; i < sitem->len; i++) { \
	    printf("%02x:", sitem->data[i]); \
    } \
    printf("\n") 
#else
#define SEC_PRINT(a, b, c, d) 
#endif /* EC_DEBUG */


SECStatus 
seckey_encrypt_private_key( PLArenaPool *permarena, NSSLOWKEYPrivateKey *pk, 
			    SDB *sdbpw, SECItem *result)
{
    NSSLOWKEYPrivateKeyInfo *pki = NULL;
    SECStatus rv = SECFailure;
    PLArenaPool *temparena = NULL;
    SECItem *der_item = NULL;
    SECItem *cipherText = NULL;
    SECItem *dummy = NULL;
#ifndef NSS_DISABLE_ECC
    SECItem *fordebug = NULL;
    int savelen;
#endif

    temparena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
    if(temparena == NULL)
	goto loser;

    /* allocate structures */
    pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(temparena, 
	sizeof(NSSLOWKEYPrivateKeyInfo));
    der_item = (SECItem *)PORT_ArenaZAlloc(temparena, sizeof(SECItem));
    if((pki == NULL) || (der_item == NULL))
	goto loser;


    /* setup private key info */
    dummy = SEC_ASN1EncodeInteger(temparena, &(pki->version), 
	NSSLOWKEY_PRIVATE_KEY_INFO_VERSION);
    if(dummy == NULL)
	goto loser;

    /* Encode the key, and set the algorithm (with params) */
    switch (pk->keyType) {
      case NSSLOWKEYRSAKey:
        lg_prepare_low_rsa_priv_key_for_asn1(pk);
	dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, 
				   lg_nsslowkey_RSAPrivateKeyTemplate);
	if (dummy == NULL) {
	    rv = SECFailure;
	    goto loser;
	}
	
	rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), 
				   SEC_OID_PKCS1_RSA_ENCRYPTION, 0);
	if (rv == SECFailure) {
	    goto loser;
	}
	
	break;
      case NSSLOWKEYDSAKey:
        lg_prepare_low_dsa_priv_key_for_asn1(pk);
	dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk,
				   lg_nsslowkey_DSAPrivateKeyTemplate);
	if (dummy == NULL) {
	    rv = SECFailure;
	    goto loser;
	}
	
        lg_prepare_low_pqg_params_for_asn1(&pk->u.dsa.params);
	dummy = SEC_ASN1EncodeItem(temparena, NULL, &pk->u.dsa.params,
				   lg_nsslowkey_PQGParamsTemplate);
	if (dummy == NULL) {
	    rv = SECFailure;
	    goto loser;
	}
	
	rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm),
				   SEC_OID_ANSIX9_DSA_SIGNATURE, dummy);
	if (rv == SECFailure) {
	    goto loser;
	}
	
	break;
      case NSSLOWKEYDHKey:
        lg_prepare_low_dh_priv_key_for_asn1(pk);
	dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk,
				   lg_nsslowkey_DHPrivateKeyTemplate);
	if (dummy == NULL) {
	    rv = SECFailure;
	    goto loser;
	}

	rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm),
				   SEC_OID_X942_DIFFIE_HELMAN_KEY, dummy);
	if (rv == SECFailure) {
	    goto loser;
	}
	break;
#ifndef NSS_DISABLE_ECC
      case NSSLOWKEYECKey:
	lg_prepare_low_ec_priv_key_for_asn1(pk);
	/* Public value is encoded as a bit string so adjust length
	 * to be in bits before ASN encoding and readjust 
	 * immediately after.
	 *
	 * Since the SECG specification recommends not including the
	 * parameters as part of ECPrivateKey, we zero out the curveOID
	 * length before encoding and restore it later.
	 */
	pk->u.ec.publicValue.len <<= 3;
	savelen = pk->u.ec.ecParams.curveOID.len;
	pk->u.ec.ecParams.curveOID.len = 0;
	dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk,
				   lg_nsslowkey_ECPrivateKeyTemplate);
	pk->u.ec.ecParams.curveOID.len = savelen;
	pk->u.ec.publicValue.len >>= 3;

	if (dummy == NULL) {
	    rv = SECFailure;
	    goto loser;
	}

	dummy = &pk->u.ec.ecParams.DEREncoding;

	/* At this point dummy should contain the encoded params */
	rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm),
				   SEC_OID_ANSIX962_EC_PUBLIC_KEY, dummy);

	if (rv == SECFailure) {
	    goto loser;
	}
	
	fordebug = &(pki->privateKey);
	SEC_PRINT("seckey_encrypt_private_key()", "PrivateKey", 
		  pk->keyType, fordebug);

	break;
#endif /* NSS_DISABLE_ECC */
      default:
	/* We don't support DH or Fortezza private keys yet */
	PORT_Assert(PR_FALSE);
	break;
    }

    /* setup encrypted private key info */
    dummy = SEC_ASN1EncodeItem(temparena, der_item, pki, 
	lg_nsslowkey_PrivateKeyInfoTemplate);

    SEC_PRINT("seckey_encrypt_private_key()", "PrivateKeyInfo", 
	      pk->keyType, der_item);

    if(dummy == NULL) {
	rv = SECFailure;
	goto loser;
    }

    rv = lg_util_encrypt(temparena, sdbpw, dummy, &cipherText);
    if (rv != SECSuccess) {
	goto loser;
    }

    rv = SECITEM_CopyItem ( permarena, result, cipherText);

loser:

    if(temparena != NULL)
	PORT_FreeArena(temparena, PR_TRUE);

    return rv;
}

static SECStatus 
seckey_put_private_key(NSSLOWKEYDBHandle *keydb, DBT *index, SDB *sdbpw,
		       NSSLOWKEYPrivateKey *pk, char *nickname, PRBool update)
{
    NSSLOWKEYDBKey *dbkey = NULL;
    PLArenaPool *arena = NULL;
    SECStatus rv = SECFailure;

    if((keydb == NULL) || (index == NULL) || (sdbpw == NULL) ||
	(pk == NULL))
	return SECFailure;
	
    arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
    if(arena == NULL)
	return SECFailure;

    dbkey = (NSSLOWKEYDBKey *)PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYDBKey));
    if(dbkey == NULL)
	goto loser;
    dbkey->arena = arena;
    dbkey->nickname = nickname;

    rv = seckey_encrypt_private_key(arena, pk, sdbpw, &dbkey->derPK);
    if(rv != SECSuccess)
	goto loser;

    rv = put_dbkey(keydb, index, dbkey, update);

    /* let success fall through */
loser:
    if(arena != NULL)
	PORT_FreeArena(arena, PR_TRUE);

    return rv;
}

/*
 * Store a key in the database, indexed by its public key modulus.
 * Note that the nickname is optional.  It was only used by keyutil.
 */
SECStatus
nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWKEYDBHandle *handle, 
			      NSSLOWKEYPrivateKey *privkey,
			      SECItem *pubKeyData,
			      char *nickname,
			      SDB *sdbpw,
                              PRBool update)
{
    DBT namekey;
    SECStatus rv;

    if (handle == NULL) {
	PORT_SetError(SEC_ERROR_BAD_DATABASE);
	return(SECFailure);
    }

    /* set up db key and data */
    namekey.data = pubKeyData->data;
    namekey.size = pubKeyData->len;

    /* encrypt the private key */
    rv = seckey_put_private_key(handle, &namekey, sdbpw, privkey, nickname,
				update);
    
    return(rv);
}

static NSSLOWKEYPrivateKey *
seckey_decrypt_private_key(SECItem*epki,
			   SDB *sdbpw)
{
    NSSLOWKEYPrivateKey *pk = NULL;
    NSSLOWKEYPrivateKeyInfo *pki = NULL;
    SECStatus rv = SECFailure;
    PLArenaPool *temparena = NULL, *permarena = NULL;
    SECItem *dest = NULL;
#ifndef NSS_DISABLE_ECC
    SECItem *fordebug = NULL;
#endif

    if((epki == NULL) || (sdbpw == NULL))
	goto loser;

    temparena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
    permarena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
    if((temparena == NULL) || (permarena == NULL))
	goto loser;

    /* allocate temporary items */
    pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(temparena, 
	sizeof(NSSLOWKEYPrivateKeyInfo));

    /* allocate permanent arena items */
    pk = (NSSLOWKEYPrivateKey *)PORT_ArenaZAlloc(permarena,
	sizeof(NSSLOWKEYPrivateKey));

    if((pk == NULL) || (pki == NULL))
	goto loser;

    pk->arena = permarena;

    rv = lg_util_decrypt(sdbpw, epki, &dest);
    if (rv != SECSuccess) {
	goto loser;
    }
	
    if(dest != NULL)
    {
        SECItem newPrivateKey;
        SECItem newAlgParms;

        SEC_PRINT("seckey_decrypt_private_key()", "PrivateKeyInfo", -1,
		  dest);

	rv = SEC_QuickDERDecodeItem(temparena, pki, 
	    lg_nsslowkey_PrivateKeyInfoTemplate, dest);
	if(rv == SECSuccess)
	{
	    switch(SECOID_GetAlgorithmTag(&pki->algorithm)) {
	      case SEC_OID_X500_RSA_ENCRYPTION:
	      case SEC_OID_PKCS1_RSA_ENCRYPTION:
		pk->keyType = NSSLOWKEYRSAKey;
		lg_prepare_low_rsa_priv_key_for_asn1(pk);
                if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey,
                    &pki->privateKey) ) break;
		rv = SEC_QuickDERDecodeItem(permarena, pk,
					lg_nsslowkey_RSAPrivateKeyTemplate,
					&newPrivateKey);
		if (rv == SECSuccess) {
		    break;
		}
		/* Try decoding with the alternative template, but only allow
		 * a zero-length modulus for a secret key object.
		 * See bug 715073.
		 */
		rv = SEC_QuickDERDecodeItem(permarena, pk,
					lg_nsslowkey_RSAPrivateKeyTemplate2,
					&newPrivateKey);
		/* A publicExponent of 0 is the defining property of a secret
		 * key disguised as an RSA key. When decoding with the
		 * alternative template, only accept a secret key with an
		 * improperly encoded modulus and a publicExponent of 0.
		 */
		if (rv == SECSuccess) {
		    if (pk->u.rsa.modulus.len == 2 &&
			pk->u.rsa.modulus.data[0] == SEC_ASN1_INTEGER &&
			pk->u.rsa.modulus.data[1] == 0 &&
			pk->u.rsa.publicExponent.len == 1 &&
			pk->u.rsa.publicExponent.data[0] == 0) {
			/* Fix the zero-length integer by setting it to 0. */
			pk->u.rsa.modulus.data = pk->u.rsa.publicExponent.data;
			pk->u.rsa.modulus.len = pk->u.rsa.publicExponent.len;
		    } else {
			PORT_SetError(SEC_ERROR_BAD_DER);
			rv = SECFailure;
		    }
		}
		break;
	      case SEC_OID_ANSIX9_DSA_SIGNATURE:
		pk->keyType = NSSLOWKEYDSAKey;
		lg_prepare_low_dsa_priv_key_for_asn1(pk);
                if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey,
                    &pki->privateKey) ) break;
		rv = SEC_QuickDERDecodeItem(permarena, pk,
					lg_nsslowkey_DSAPrivateKeyTemplate,
					&newPrivateKey);
		if (rv != SECSuccess)
		    goto loser;
		lg_prepare_low_pqg_params_for_asn1(&pk->u.dsa.params);
                if (SECSuccess != SECITEM_CopyItem(permarena, &newAlgParms,
                    &pki->algorithm.parameters) ) break;
		rv = SEC_QuickDERDecodeItem(permarena, &pk->u.dsa.params,
					lg_nsslowkey_PQGParamsTemplate,
					&newAlgParms);
		break;
	      case SEC_OID_X942_DIFFIE_HELMAN_KEY:
		pk->keyType = NSSLOWKEYDHKey;
		lg_prepare_low_dh_priv_key_for_asn1(pk);
                if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey,
                    &pki->privateKey) ) break;
		rv = SEC_QuickDERDecodeItem(permarena, pk,
					lg_nsslowkey_DHPrivateKeyTemplate,
					&newPrivateKey);
		break;
#ifndef NSS_DISABLE_ECC
	      case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
		pk->keyType = NSSLOWKEYECKey;
		lg_prepare_low_ec_priv_key_for_asn1(pk);

		fordebug = &pki->privateKey;
		SEC_PRINT("seckey_decrypt_private_key()", "PrivateKey", 
			  pk->keyType, fordebug);
                if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey,
                    &pki->privateKey) ) break;
		rv = SEC_QuickDERDecodeItem(permarena, pk,
					lg_nsslowkey_ECPrivateKeyTemplate,
					&newPrivateKey);
		if (rv != SECSuccess)
		    goto loser;

		lg_prepare_low_ecparams_for_asn1(&pk->u.ec.ecParams);

		rv = SECITEM_CopyItem(permarena, 
		    &pk->u.ec.ecParams.DEREncoding, 
		    &pki->algorithm.parameters);

		if (rv != SECSuccess)
		    goto loser;

		/* Fill out the rest of EC params */
		rv = LGEC_FillParams(permarena, &pk->u.ec.ecParams.DEREncoding,
				   &pk->u.ec.ecParams);

		if (rv != SECSuccess)
		    goto loser;

		if (pk->u.ec.publicValue.len != 0) {
		    pk->u.ec.publicValue.len >>= 3;
		}

		break;
#endif /* NSS_DISABLE_ECC */
	      default:
		rv = SECFailure;
		break;
	    }
	}
	else if(PORT_GetError() == SEC_ERROR_BAD_DER)
	{
	    PORT_SetError(SEC_ERROR_BAD_PASSWORD);
	    goto loser;
	}
    }

    /* let success fall through */
loser:
    if(temparena != NULL)
	PORT_FreeArena(temparena, PR_TRUE);
    if(dest != NULL)
	SECITEM_ZfreeItem(dest, PR_TRUE);

    if(rv != SECSuccess)
    {
	if(permarena != NULL)
	    PORT_FreeArena(permarena, PR_TRUE);
	pk = NULL;
    }

    return pk;
}

static NSSLOWKEYPrivateKey *
seckey_decode_encrypted_private_key(NSSLOWKEYDBKey *dbkey, SDB *sdbpw)
{
    if( ( dbkey == NULL ) || ( sdbpw == NULL ) ) {
	return NULL;
    }

    return seckey_decrypt_private_key(&(dbkey->derPK), sdbpw);
}

static NSSLOWKEYPrivateKey *
seckey_get_private_key(NSSLOWKEYDBHandle *keydb, DBT *index, char **nickname,
		       SDB *sdbpw)
{
    NSSLOWKEYDBKey *dbkey = NULL;
    NSSLOWKEYPrivateKey *pk = NULL;

    if( ( keydb == NULL ) || ( index == NULL ) || ( sdbpw == NULL ) ) {
	return NULL;
    }

    dbkey = get_dbkey(keydb, index);
    if(dbkey == NULL) {
	goto loser;
    }
    
    if ( nickname ) {
	if ( dbkey->nickname && ( dbkey->nickname[0] != 0 ) ) {
	    *nickname = PORT_Strdup(dbkey->nickname);
	} else {
	    *nickname = NULL;
	}
    }
    
    pk = seckey_decode_encrypted_private_key(dbkey, sdbpw);
    
    /* let success fall through */
loser:

    if ( dbkey != NULL ) {
	sec_destroy_dbkey(dbkey);
    }

    return pk;
}

/*
 * Find a key in the database, indexed by its public key modulus
 * This is used to find keys that have been stored before their
 * certificate arrives.  Once the certificate arrives the key
 * is looked up by the public modulus in the certificate, and the
 * re-stored by its nickname.
 */
NSSLOWKEYPrivateKey *
nsslowkey_FindKeyByPublicKey(NSSLOWKEYDBHandle *handle, SECItem *modulus,
			  				 SDB *sdbpw)
{
    DBT namekey;
    NSSLOWKEYPrivateKey *pk = NULL;

    if (handle == NULL) {
	PORT_SetError(SEC_ERROR_BAD_DATABASE);
	return NULL;
    }

    /* set up db key */
    namekey.data = modulus->data;
    namekey.size = modulus->len;

    pk = seckey_get_private_key(handle, &namekey, NULL, sdbpw);
    
    /* no need to free dbkey, since its on the stack, and the data it
     * points to is owned by the database
     */
    return(pk);
}

char *
nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle, 
					SECItem *modulus, SDB *sdbpw)
{
    DBT namekey;
    NSSLOWKEYPrivateKey *pk = NULL;
    char *nickname = NULL;

    if (handle == NULL) {
	PORT_SetError(SEC_ERROR_BAD_DATABASE);
	return NULL;
    }

    /* set up db key */
    namekey.data = modulus->data;
    namekey.size = modulus->len;

    pk = seckey_get_private_key(handle, &namekey, &nickname, sdbpw);
    if (pk) {
	lg_nsslowkey_DestroyPrivateKey(pk);
    }
    
    /* no need to free dbkey, since its on the stack, and the data it
     * points to is owned by the database
     */
    return(nickname);
}
/* ===== ENCODING ROUTINES ===== */

static SECStatus
encodePWCheckEntry(PLArenaPool *arena, SECItem *entry, SECOidTag alg,
		   SECItem *encCheck)
{
    SECOidData *oidData;
    SECStatus rv;
    
    oidData = SECOID_FindOIDByTag(alg);
    if ( oidData == NULL ) {
	rv = SECFailure;
	goto loser;
    }

    entry->len = 1 + oidData->oid.len + encCheck->len;
    if ( arena ) {
	entry->data = (unsigned char *)PORT_ArenaAlloc(arena, entry->len);
    } else {
	entry->data = (unsigned char *)PORT_Alloc(entry->len);
    }
    
    if ( entry->data == NULL ) {
	goto loser;
    }
	
    /* first length of oid */
    entry->data[0] = (unsigned char)oidData->oid.len;
    /* next oid itself */
    PORT_Memcpy(&entry->data[1], oidData->oid.data, oidData->oid.len);
    /* finally the encrypted check string */
    PORT_Memcpy(&entry->data[1+oidData->oid.len], encCheck->data,
		encCheck->len);

    return(SECSuccess);

loser:
    return(SECFailure);
}
    

#define MAX_DB_SIZE 0xffff 
/*
 * Clear out all the keys in the existing database
 */
static SECStatus
nsslowkey_ResetKeyDB(NSSLOWKEYDBHandle *handle)
{
    SECStatus rv;
    int ret;
    int errors = 0;

    if ( handle->db == NULL ) {
	return(SECSuccess);
    }

    if (handle->readOnly) {
	/* set an error code */
	return SECFailure;
     }

    if (handle->appname == NULL && handle->dbname == NULL) {
	return SECFailure;
    }

    keydb_Close(handle);
    if (handle->appname) {
	handle->db= 
	    rdbopen(handle->appname, handle->dbname, "key", NO_CREATE, NULL);
    } else {
	handle->db = dbopen( handle->dbname, NO_CREATE, 0600, DB_HASH, 0 );
    }
    if (handle->db == NULL) {
	/* set an error code */
	return SECFailure;
    }
    
    rv = makeGlobalVersion(handle);
    if ( rv != SECSuccess ) {
	errors++;
	goto done;
    }

    if (handle->global_salt) {
	rv = StoreKeyDBGlobalSalt(handle, handle->global_salt);
    } else {
	rv = makeGlobalSalt(handle);
	if ( rv == SECSuccess ) {
	    handle->global_salt = GetKeyDBGlobalSalt(handle);
	}
    }
    if ( rv != SECSuccess ) {
	errors++;
    }

done:
    /* sync the database */
    ret = keydb_Sync(handle, 0);
    db_InitComplete(handle->db);

    return (errors == 0 ? SECSuccess : SECFailure);
}

static int
keydb_Get(NSSLOWKEYDBHandle *kdb, DBT *key, DBT *data, unsigned int flags)
{
    PRStatus prstat;
    int ret;
    PRLock *kdbLock = kdb->lock;
    DB *db = kdb->db;
    
    PORT_Assert(kdbLock != NULL);
    PZ_Lock(kdbLock);

    ret = (* db->get)(db, key, data, flags);

    prstat = PZ_Unlock(kdbLock);

    return(ret);
}

static int
keydb_Put(NSSLOWKEYDBHandle *kdb, DBT *key, DBT *data, unsigned int flags)
{
    PRStatus prstat;
    int ret = 0;
    PRLock *kdbLock = kdb->lock;
    DB *db = kdb->db;

    PORT_Assert(kdbLock != NULL);
    PZ_Lock(kdbLock);

    ret = (* db->put)(db, key, data, flags);
    
    prstat = PZ_Unlock(kdbLock);

    return(ret);
}

static int
keydb_Sync(NSSLOWKEYDBHandle *kdb, unsigned int flags)
{
    PRStatus prstat;
    int ret;
    PRLock *kdbLock = kdb->lock;
    DB *db = kdb->db;

    PORT_Assert(kdbLock != NULL);
    PZ_Lock(kdbLock);

    ret = (* db->sync)(db, flags);
    
    prstat = PZ_Unlock(kdbLock);

    return(ret);
}

static int
keydb_Del(NSSLOWKEYDBHandle *kdb, DBT *key, unsigned int flags)
{
    PRStatus prstat;
    int ret;
    PRLock *kdbLock = kdb->lock;
    DB *db = kdb->db;

    PORT_Assert(kdbLock != NULL);
    PZ_Lock(kdbLock);

    ret = (* db->del)(db, key, flags);
    
    prstat = PZ_Unlock(kdbLock);

    return(ret);
}

static int
keydb_Seq(NSSLOWKEYDBHandle *kdb, DBT *key, DBT *data, unsigned int flags)
{
    PRStatus prstat;
    int ret;
    PRLock *kdbLock = kdb->lock;
    DB *db = kdb->db;
    
    PORT_Assert(kdbLock != NULL);
    PZ_Lock(kdbLock);
    
    ret = (* db->seq)(db, key, data, flags);

    prstat = PZ_Unlock(kdbLock);

    return(ret);
}

static void
keydb_Close(NSSLOWKEYDBHandle *kdb)
{
    PRStatus prstat;
    PRLock *kdbLock = kdb->lock;
    DB *db = kdb->db;

    PORT_Assert(kdbLock != NULL);
    SKIP_AFTER_FORK(PZ_Lock(kdbLock));

    (* db->close)(db);
    
    SKIP_AFTER_FORK(prstat = PZ_Unlock(kdbLock));

    return;
}

/*
 * SDB Entry Points for the Key DB 
 */

CK_RV
lg_GetMetaData(SDB *sdb, const char *id, SECItem *item1, SECItem *item2)
{
    NSSLOWKEYDBHandle *keydb;
    NSSLOWKEYPasswordEntry entry;
    SECStatus rv;

    keydb = lg_getKeyDB(sdb);
    if (keydb == NULL) {
        return CKR_TOKEN_WRITE_PROTECTED;
    }
    if (PORT_Strcmp(id,"password") != 0) {
	/* shouldn't happen */
	return CKR_GENERAL_ERROR; /* no extra data stored */
    }
    rv = nsslowkey_GetPWCheckEntry(keydb, &entry);
    if (rv != SECSuccess) {
        return CKR_GENERAL_ERROR;
    }
    item1->len = entry.salt.len;
    PORT_Memcpy(item1->data, entry.salt.data, item1->len);
    item2->len = entry.value.len;
    PORT_Memcpy(item2->data, entry.value.data, item2->len);
    return CKR_OK;
}

CK_RV
lg_PutMetaData(SDB *sdb, const char *id, 
	       const SECItem *item1, const SECItem *item2)
{
    NSSLOWKEYDBHandle *keydb;
    NSSLOWKEYPasswordEntry entry;
    SECStatus rv;

    keydb = lg_getKeyDB(sdb);
    if (keydb == NULL) {
        return CKR_TOKEN_WRITE_PROTECTED;
    }
    if (PORT_Strcmp(id,"password") != 0) {
	/* shouldn't happen */
	return CKR_GENERAL_ERROR; /* no extra data stored */
    }
    entry.salt = *item1;
    entry.value = *item2;
    rv = nsslowkey_PutPWCheckEntry(keydb, &entry);
    if (rv != SECSuccess) {
        return CKR_GENERAL_ERROR;
    }
    return CKR_OK;
}

CK_RV
lg_Reset(SDB *sdb)
{
    NSSLOWKEYDBHandle *keydb;
    SECStatus rv;

    keydb = lg_getKeyDB(sdb);
    if (keydb == NULL) {
        return CKR_TOKEN_WRITE_PROTECTED;
    }
    rv = nsslowkey_ResetKeyDB(keydb);
    if (rv != SECSuccess) {
        return CKR_GENERAL_ERROR;
    }
    return CKR_OK;
}