summaryrefslogtreecommitdiffstats
path: root/security/nss/lib/pkcs12/p12e.c
blob: cce1ff7c09a115ee5868b164d67368c91a876e50 (plain)
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
/* 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 "p12t.h"
#include "p12.h"
#include "plarena.h"
#include "secitem.h"
#include "secoid.h"
#include "seccomon.h"
#include "secport.h"
#include "cert.h"
#include "secpkcs7.h"
#include "secasn1.h"
#include "secerr.h"
#include "pk11func.h"
#include "p12plcy.h"
#include "p12local.h"
#include "prcpucfg.h"

extern const int NSS_PBE_DEFAULT_ITERATION_COUNT; /* defined in p7create.c */

/*
** This PKCS12 file encoder uses numerous nested ASN.1 and PKCS7 encoder
** contexts.  It can be difficult to keep straight.  Here's a picture:
**
**  "outer"  ASN.1 encoder.  The output goes to the library caller's CB.
**  "middle" PKCS7 encoder.  Feeds    the "outer" ASN.1 encoder.
**  "middle" ASN1  encoder.  Encodes  the encrypted aSafes.
**                           Feeds    the "middle" P7 encoder above.
**  "inner"  PKCS7 encoder.  Encrypts the "authenticated Safes" (aSafes)
**                           Feeds    the "middle" ASN.1 encoder above.
**  "inner"  ASN.1 encoder.  Encodes  the unencrypted aSafes.
**                           Feeds    the "inner" P7 enocder above.
**
** Buffering has been added at each point where the output of an ASN.1
** encoder feeds the input of a PKCS7 encoder.
*/

/*********************************
 * Output buffer object, used to buffer output from ASN.1 encoder
 * before passing data on down to the next PKCS7 encoder.
 *********************************/

#define PK12_OUTPUT_BUFFER_SIZE 8192

struct sec_pkcs12OutputBufferStr {
    SEC_PKCS7EncoderContext *p7eCx;
    PK11Context *hmacCx;
    unsigned int numBytes;
    unsigned int bufBytes;
    char buf[PK12_OUTPUT_BUFFER_SIZE];
};
typedef struct sec_pkcs12OutputBufferStr sec_pkcs12OutputBuffer;

/*********************************
 * Structures used in exporting the PKCS 12 blob
 *********************************/

/* A SafeInfo is used for each ContentInfo which makes up the
 * sequence of safes in the AuthenticatedSafe portion of the
 * PFX structure.
 */
struct SEC_PKCS12SafeInfoStr {
    PLArenaPool *arena;

    /* information for setting up password encryption */
    SECItem pwitem;
    SECOidTag algorithm;
    PK11SymKey *encryptionKey;

    /* how many items have been stored in this safe,
     * we will skip any safe which does not contain any
     * items
     */
    unsigned int itemCount;

    /* the content info for the safe */
    SEC_PKCS7ContentInfo *cinfo;

    sec_PKCS12SafeContents *safe;
};

/* An opaque structure which contains information needed for exporting
 * certificates and keys through PKCS 12.
 */
struct SEC_PKCS12ExportContextStr {
    PLArenaPool *arena;
    PK11SlotInfo *slot;
    void *wincx;

    /* integrity information */
    PRBool integrityEnabled;
    PRBool pwdIntegrity;
    union {
        struct sec_PKCS12PasswordModeInfo pwdInfo;
        struct sec_PKCS12PublicKeyModeInfo pubkeyInfo;
    } integrityInfo;

    /* helper functions */
    /* retrieve the password call back */
    SECKEYGetPasswordKey pwfn;
    void *pwfnarg;

    /* safe contents bags */
    SEC_PKCS12SafeInfo **safeInfos;
    unsigned int safeInfoCount;

    /* the sequence of safes */
    sec_PKCS12AuthenticatedSafe authSafe;

    /* information needing deletion */
    CERTCertificate **certList;
};

/* structures for passing information to encoder callbacks when processing
 * data through the ASN1 engine.
 */
struct sec_pkcs12_encoder_output {
    SEC_PKCS12EncoderOutputCallback outputfn;
    void *outputarg;
};

struct sec_pkcs12_hmac_and_output_info {
    void *arg;
    struct sec_pkcs12_encoder_output output;
};

/* An encoder context which is used for the actual encoding
 * portion of PKCS 12.
 */
typedef struct sec_PKCS12EncoderContextStr {
    PLArenaPool *arena;
    SEC_PKCS12ExportContext *p12exp;

    /* encoder information - this is set up based on whether
     * password based or public key pased privacy is being used
     */
    SEC_ASN1EncoderContext *outerA1ecx;
    union {
        struct sec_pkcs12_hmac_and_output_info hmacAndOutputInfo;
        struct sec_pkcs12_encoder_output encOutput;
    } output;

    /* structures for encoding of PFX and MAC */
    sec_PKCS12PFXItem pfx;
    sec_PKCS12MacData mac;

    /* authenticated safe encoding tracking information */
    SEC_PKCS7ContentInfo *aSafeCinfo;
    SEC_PKCS7EncoderContext *middleP7ecx;
    SEC_ASN1EncoderContext *middleA1ecx;
    unsigned int currentSafe;

    /* hmac context */
    PK11Context *hmacCx;

    /* output buffers */
    sec_pkcs12OutputBuffer middleBuf;
    sec_pkcs12OutputBuffer innerBuf;

} sec_PKCS12EncoderContext;

/*********************************
 * Export setup routines
 *********************************/

/* SEC_PKCS12CreateExportContext
 *   Creates an export context and sets the unicode and password retrieval
 *   callbacks.  This is the first call which must be made when exporting
 *   a PKCS 12 blob.
 *
 * pwfn, pwfnarg - password retrieval callback and argument.  these are
 *                 required for password-authentication mode.
 */
SEC_PKCS12ExportContext *
SEC_PKCS12CreateExportContext(SECKEYGetPasswordKey pwfn, void *pwfnarg,
                              PK11SlotInfo *slot, void *wincx)
{
    PLArenaPool *arena = NULL;
    SEC_PKCS12ExportContext *p12ctxt = NULL;

    /* allocate the arena and create the context */
    arena = PORT_NewArena(4096);
    if (!arena) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    p12ctxt = (SEC_PKCS12ExportContext *)PORT_ArenaZAlloc(arena,
                                                          sizeof(SEC_PKCS12ExportContext));
    if (!p12ctxt) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* password callback for key retrieval */
    p12ctxt->pwfn = pwfn;
    p12ctxt->pwfnarg = pwfnarg;

    p12ctxt->integrityEnabled = PR_FALSE;
    p12ctxt->arena = arena;
    p12ctxt->wincx = wincx;
    p12ctxt->slot = (slot) ? PK11_ReferenceSlot(slot) : PK11_GetInternalSlot();

    return p12ctxt;

loser:
    if (arena) {
        PORT_FreeArena(arena, PR_TRUE);
    }

    return NULL;
}

/*
 * Adding integrity mode
 */

/* SEC_PKCS12AddPasswordIntegrity
 *      Add password integrity to the exported data.  If an integrity method
 *      has already been set, then return an error.
 *
 *      p12ctxt - the export context
 *      pwitem - the password for integrity mode
 *      integAlg - the integrity algorithm to use for authentication.
 */
SECStatus
SEC_PKCS12AddPasswordIntegrity(SEC_PKCS12ExportContext *p12ctxt,
                               SECItem *pwitem, SECOidTag integAlg)
{
    if (!p12ctxt || p12ctxt->integrityEnabled) {
        return SECFailure;
    }

    /* set up integrity information */
    p12ctxt->pwdIntegrity = PR_TRUE;
    p12ctxt->integrityInfo.pwdInfo.password =
        (SECItem *)PORT_ArenaZAlloc(p12ctxt->arena, sizeof(SECItem));
    if (!p12ctxt->integrityInfo.pwdInfo.password) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }
    if (SECITEM_CopyItem(p12ctxt->arena,
                         p12ctxt->integrityInfo.pwdInfo.password, pwitem) != SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }
    p12ctxt->integrityInfo.pwdInfo.algorithm = integAlg;
    p12ctxt->integrityEnabled = PR_TRUE;

    return SECSuccess;
}

/* SEC_PKCS12AddPublicKeyIntegrity
 *      Add public key integrity to the exported data.  If an integrity method
 *      has already been set, then return an error.  The certificate must be
 *      allowed to be used as a signing cert.
 *
 *      p12ctxt - the export context
 *      cert - signer certificate
 *      certDb - the certificate database
 *      algorithm - signing algorithm
 *      keySize - size of the signing key (?)
 */
SECStatus
SEC_PKCS12AddPublicKeyIntegrity(SEC_PKCS12ExportContext *p12ctxt,
                                CERTCertificate *cert, CERTCertDBHandle *certDb,
                                SECOidTag algorithm, int keySize)
{
    if (!p12ctxt) {
        return SECFailure;
    }

    p12ctxt->integrityInfo.pubkeyInfo.cert = cert;
    p12ctxt->integrityInfo.pubkeyInfo.certDb = certDb;
    p12ctxt->integrityInfo.pubkeyInfo.algorithm = algorithm;
    p12ctxt->integrityInfo.pubkeyInfo.keySize = keySize;
    p12ctxt->integrityEnabled = PR_TRUE;

    return SECSuccess;
}

/*
 * Adding safes - encrypted (password/public key) or unencrypted
 *      Each of the safe creation routines return an opaque pointer which
 *      are later passed into the routines for exporting certificates and
 *      keys.
 */

/* append the newly created safeInfo to list of safeInfos in the export
 * context.
 */
static SECStatus
sec_pkcs12_append_safe_info(SEC_PKCS12ExportContext *p12ctxt, SEC_PKCS12SafeInfo *info)
{
    void *mark = NULL, *dummy1 = NULL, *dummy2 = NULL;

    if (!p12ctxt || !info) {
        return SECFailure;
    }

    mark = PORT_ArenaMark(p12ctxt->arena);

    /* if no safeInfos have been set, create the list, otherwise expand it. */
    if (!p12ctxt->safeInfoCount) {
        p12ctxt->safeInfos = (SEC_PKCS12SafeInfo **)PORT_ArenaZAlloc(p12ctxt->arena,
                                                                     2 * sizeof(SEC_PKCS12SafeInfo *));
        dummy1 = p12ctxt->safeInfos;
        p12ctxt->authSafe.encodedSafes = (SECItem **)PORT_ArenaZAlloc(p12ctxt->arena,
                                                                      2 * sizeof(SECItem *));
        dummy2 = p12ctxt->authSafe.encodedSafes;
    } else {
        dummy1 = PORT_ArenaGrow(p12ctxt->arena, p12ctxt->safeInfos,
                                (p12ctxt->safeInfoCount + 1) * sizeof(SEC_PKCS12SafeInfo *),
                                (p12ctxt->safeInfoCount + 2) * sizeof(SEC_PKCS12SafeInfo *));
        p12ctxt->safeInfos = (SEC_PKCS12SafeInfo **)dummy1;
        dummy2 = PORT_ArenaGrow(p12ctxt->arena, p12ctxt->authSafe.encodedSafes,
                                (p12ctxt->authSafe.safeCount + 1) * sizeof(SECItem *),
                                (p12ctxt->authSafe.safeCount + 2) * sizeof(SECItem *));
        p12ctxt->authSafe.encodedSafes = (SECItem **)dummy2;
    }
    if (!dummy1 || !dummy2) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* append the new safeInfo and null terminate the list */
    p12ctxt->safeInfos[p12ctxt->safeInfoCount] = info;
    p12ctxt->safeInfos[++p12ctxt->safeInfoCount] = NULL;
    p12ctxt->authSafe.encodedSafes[p12ctxt->authSafe.safeCount] =
        (SECItem *)PORT_ArenaZAlloc(p12ctxt->arena, sizeof(SECItem));
    if (!p12ctxt->authSafe.encodedSafes[p12ctxt->authSafe.safeCount]) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }
    p12ctxt->authSafe.encodedSafes[++p12ctxt->authSafe.safeCount] = NULL;

    PORT_ArenaUnmark(p12ctxt->arena, mark);
    return SECSuccess;

loser:
    PORT_ArenaRelease(p12ctxt->arena, mark);
    return SECFailure;
}

/* SEC_PKCS12CreatePasswordPrivSafe
 *      Create a password privacy safe to store exported information in.
 *
 *      p12ctxt - export context
 *      pwitem - password for encryption
 *      privAlg - pbe algorithm through which encryption is done.
 */
SEC_PKCS12SafeInfo *
SEC_PKCS12CreatePasswordPrivSafe(SEC_PKCS12ExportContext *p12ctxt,
                                 SECItem *pwitem, SECOidTag privAlg)
{
    SEC_PKCS12SafeInfo *safeInfo = NULL;
    void *mark = NULL;
    PK11SlotInfo *slot = NULL;
    SECAlgorithmID *algId;
    SECItem uniPwitem = { siBuffer, NULL, 0 };

    if (!p12ctxt) {
        return NULL;
    }

    /* allocate the safe info */
    mark = PORT_ArenaMark(p12ctxt->arena);
    safeInfo = (SEC_PKCS12SafeInfo *)PORT_ArenaZAlloc(p12ctxt->arena,
                                                      sizeof(SEC_PKCS12SafeInfo));
    if (!safeInfo) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        PORT_ArenaRelease(p12ctxt->arena, mark);
        return NULL;
    }

    safeInfo->itemCount = 0;

    /* create the encrypted safe */
    safeInfo->cinfo = SEC_PKCS7CreateEncryptedData(privAlg, 0, p12ctxt->pwfn,
                                                   p12ctxt->pwfnarg);
    if (!safeInfo->cinfo) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }
    safeInfo->arena = p12ctxt->arena;

    /* convert the password to unicode */
    if (!sec_pkcs12_convert_item_to_unicode(NULL, &uniPwitem, pwitem,
                                            PR_TRUE, PR_TRUE, PR_TRUE)) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }
    if (SECITEM_CopyItem(p12ctxt->arena, &safeInfo->pwitem, &uniPwitem) != SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* generate the encryption key */
    slot = PK11_ReferenceSlot(p12ctxt->slot);
    if (!slot) {
        slot = PK11_GetInternalKeySlot();
        if (!slot) {
            PORT_SetError(SEC_ERROR_NO_MEMORY);
            goto loser;
        }
    }

    algId = SEC_PKCS7GetEncryptionAlgorithm(safeInfo->cinfo);
    safeInfo->encryptionKey = PK11_PBEKeyGen(slot, algId, &uniPwitem,
                                             PR_FALSE, p12ctxt->wincx);
    if (!safeInfo->encryptionKey) {
        goto loser;
    }

    safeInfo->arena = p12ctxt->arena;
    safeInfo->safe = NULL;
    if (sec_pkcs12_append_safe_info(p12ctxt, safeInfo) != SECSuccess) {
        goto loser;
    }

    if (uniPwitem.data) {
        SECITEM_ZfreeItem(&uniPwitem, PR_FALSE);
    }
    PORT_ArenaUnmark(p12ctxt->arena, mark);

    if (slot) {
        PK11_FreeSlot(slot);
    }
    return safeInfo;

loser:
    if (slot) {
        PK11_FreeSlot(slot);
    }
    if (safeInfo->cinfo) {
        SEC_PKCS7DestroyContentInfo(safeInfo->cinfo);
    }

    if (uniPwitem.data) {
        SECITEM_ZfreeItem(&uniPwitem, PR_FALSE);
    }

    PORT_ArenaRelease(p12ctxt->arena, mark);
    return NULL;
}

/* SEC_PKCS12CreateUnencryptedSafe
 *      Creates an unencrypted safe within the export context.
 *
 *      p12ctxt - the export context
 */
SEC_PKCS12SafeInfo *
SEC_PKCS12CreateUnencryptedSafe(SEC_PKCS12ExportContext *p12ctxt)
{
    SEC_PKCS12SafeInfo *safeInfo = NULL;
    void *mark = NULL;

    if (!p12ctxt) {
        return NULL;
    }

    /* create the safe info */
    mark = PORT_ArenaMark(p12ctxt->arena);
    safeInfo = (SEC_PKCS12SafeInfo *)PORT_ArenaZAlloc(p12ctxt->arena,
                                                      sizeof(SEC_PKCS12SafeInfo));
    if (!safeInfo) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    safeInfo->itemCount = 0;

    /* create the safe content */
    safeInfo->cinfo = SEC_PKCS7CreateData();
    if (!safeInfo->cinfo) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    if (sec_pkcs12_append_safe_info(p12ctxt, safeInfo) != SECSuccess) {
        goto loser;
    }

    PORT_ArenaUnmark(p12ctxt->arena, mark);
    return safeInfo;

loser:
    if (safeInfo->cinfo) {
        SEC_PKCS7DestroyContentInfo(safeInfo->cinfo);
    }

    PORT_ArenaRelease(p12ctxt->arena, mark);
    return NULL;
}

/* SEC_PKCS12CreatePubKeyEncryptedSafe
 *      Creates a safe which is protected by public key encryption.
 *
 *      p12ctxt - the export context
 *      certDb - the certificate database
 *      signer - the signer's certificate
 *      recipients - the list of recipient certificates.
 *      algorithm - the encryption algorithm to use
 *      keysize - the algorithms key size (?)
 */
SEC_PKCS12SafeInfo *
SEC_PKCS12CreatePubKeyEncryptedSafe(SEC_PKCS12ExportContext *p12ctxt,
                                    CERTCertDBHandle *certDb,
                                    CERTCertificate *signer,
                                    CERTCertificate **recipients,
                                    SECOidTag algorithm, int keysize)
{
    SEC_PKCS12SafeInfo *safeInfo = NULL;
    void *mark = NULL;

    if (!p12ctxt || !signer || !recipients || !(*recipients)) {
        return NULL;
    }

    /* allocate the safeInfo */
    mark = PORT_ArenaMark(p12ctxt->arena);
    safeInfo = (SEC_PKCS12SafeInfo *)PORT_ArenaZAlloc(p12ctxt->arena,
                                                      sizeof(SEC_PKCS12SafeInfo));
    if (!safeInfo) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    safeInfo->itemCount = 0;
    safeInfo->arena = p12ctxt->arena;

    /* create the enveloped content info using certUsageEmailSigner currently.
     * XXX We need to eventually use something other than certUsageEmailSigner
     */
    safeInfo->cinfo = SEC_PKCS7CreateEnvelopedData(signer, certUsageEmailSigner,
                                                   certDb, algorithm, keysize,
                                                   p12ctxt->pwfn, p12ctxt->pwfnarg);
    if (!safeInfo->cinfo) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* add recipients */
    if (recipients) {
        unsigned int i = 0;
        while (recipients[i] != NULL) {
            SECStatus rv = SEC_PKCS7AddRecipient(safeInfo->cinfo, recipients[i],
                                                 certUsageEmailRecipient, certDb);
            if (rv != SECSuccess) {
                goto loser;
            }
            i++;
        }
    }

    if (sec_pkcs12_append_safe_info(p12ctxt, safeInfo) != SECSuccess) {
        goto loser;
    }

    PORT_ArenaUnmark(p12ctxt->arena, mark);
    return safeInfo;

loser:
    if (safeInfo->cinfo) {
        SEC_PKCS7DestroyContentInfo(safeInfo->cinfo);
        safeInfo->cinfo = NULL;
    }

    PORT_ArenaRelease(p12ctxt->arena, mark);
    return NULL;
}

/*********************************
 * Routines to handle the exporting of the keys and certificates
 *********************************/

/* creates a safe contents which safeBags will be appended to */
sec_PKCS12SafeContents *
sec_PKCS12CreateSafeContents(PLArenaPool *arena)
{
    sec_PKCS12SafeContents *safeContents;

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

    /* create the safe contents */
    safeContents = (sec_PKCS12SafeContents *)PORT_ArenaZAlloc(arena,
                                                              sizeof(sec_PKCS12SafeContents));
    if (!safeContents) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* set up the internal contents info */
    safeContents->safeBags = NULL;
    safeContents->arena = arena;
    safeContents->bagCount = 0;

    return safeContents;

loser:
    return NULL;
}

/* appends a safe bag to a safeContents using the specified arena.
 */
SECStatus
sec_pkcs12_append_bag_to_safe_contents(PLArenaPool *arena,
                                       sec_PKCS12SafeContents *safeContents,
                                       sec_PKCS12SafeBag *safeBag)
{
    void *mark = NULL, *dummy = NULL;

    if (!arena || !safeBag || !safeContents) {
        return SECFailure;
    }

    mark = PORT_ArenaMark(arena);
    if (!mark) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }

    /* allocate space for the list, or reallocate to increase space */
    if (!safeContents->safeBags) {
        safeContents->safeBags = (sec_PKCS12SafeBag **)PORT_ArenaZAlloc(arena,
                                                                        (2 * sizeof(sec_PKCS12SafeBag *)));
        dummy = safeContents->safeBags;
        safeContents->bagCount = 0;
    } else {
        dummy = PORT_ArenaGrow(arena, safeContents->safeBags,
                               (safeContents->bagCount + 1) * sizeof(sec_PKCS12SafeBag *),
                               (safeContents->bagCount + 2) * sizeof(sec_PKCS12SafeBag *));
        safeContents->safeBags = (sec_PKCS12SafeBag **)dummy;
    }

    if (!dummy) {
        PORT_ArenaRelease(arena, mark);
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }

    /* append the bag at the end and null terminate the list */
    safeContents->safeBags[safeContents->bagCount++] = safeBag;
    safeContents->safeBags[safeContents->bagCount] = NULL;

    PORT_ArenaUnmark(arena, mark);

    return SECSuccess;
}

/* appends a safeBag to a specific safeInfo.
 */
SECStatus
sec_pkcs12_append_bag(SEC_PKCS12ExportContext *p12ctxt,
                      SEC_PKCS12SafeInfo *safeInfo, sec_PKCS12SafeBag *safeBag)
{
    sec_PKCS12SafeContents *dest;
    SECStatus rv = SECFailure;

    if (!p12ctxt || !safeBag || !safeInfo) {
        return SECFailure;
    }

    if (!safeInfo->safe) {
        safeInfo->safe = sec_PKCS12CreateSafeContents(p12ctxt->arena);
        if (!safeInfo->safe) {
            return SECFailure;
        }
    }

    dest = safeInfo->safe;
    rv = sec_pkcs12_append_bag_to_safe_contents(p12ctxt->arena, dest, safeBag);
    if (rv == SECSuccess) {
        safeInfo->itemCount++;
    }

    return rv;
}

/* Creates a safeBag of the specified type, and if bagData is specified,
 * the contents are set.  The contents could be set later by the calling
 * routine.
 */
sec_PKCS12SafeBag *
sec_PKCS12CreateSafeBag(SEC_PKCS12ExportContext *p12ctxt, SECOidTag bagType,
                        void *bagData)
{
    sec_PKCS12SafeBag *safeBag;
    void *mark = NULL;
    SECStatus rv = SECSuccess;
    SECOidData *oidData = NULL;

    if (!p12ctxt) {
        return NULL;
    }

    mark = PORT_ArenaMark(p12ctxt->arena);
    if (!mark) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    safeBag = (sec_PKCS12SafeBag *)PORT_ArenaZAlloc(p12ctxt->arena,
                                                    sizeof(sec_PKCS12SafeBag));
    if (!safeBag) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    /* set the bags content based upon bag type */
    switch (bagType) {
        case SEC_OID_PKCS12_V1_KEY_BAG_ID:
            safeBag->safeBagContent.pkcs8KeyBag =
                (SECKEYPrivateKeyInfo *)bagData;
            break;
        case SEC_OID_PKCS12_V1_CERT_BAG_ID:
            safeBag->safeBagContent.certBag = (sec_PKCS12CertBag *)bagData;
            break;
        case SEC_OID_PKCS12_V1_CRL_BAG_ID:
            safeBag->safeBagContent.crlBag = (sec_PKCS12CRLBag *)bagData;
            break;
        case SEC_OID_PKCS12_V1_SECRET_BAG_ID:
            safeBag->safeBagContent.secretBag = (sec_PKCS12SecretBag *)bagData;
            break;
        case SEC_OID_PKCS12_V1_PKCS8_SHROUDED_KEY_BAG_ID:
            safeBag->safeBagContent.pkcs8ShroudedKeyBag =
                (SECKEYEncryptedPrivateKeyInfo *)bagData;
            break;
        case SEC_OID_PKCS12_V1_SAFE_CONTENTS_BAG_ID:
            safeBag->safeBagContent.safeContents =
                (sec_PKCS12SafeContents *)bagData;
            break;
        default:
            goto loser;
    }

    oidData = SECOID_FindOIDByTag(bagType);
    if (oidData) {
        rv = SECITEM_CopyItem(p12ctxt->arena, &safeBag->safeBagType, &oidData->oid);
        if (rv != SECSuccess) {
            PORT_SetError(SEC_ERROR_NO_MEMORY);
            goto loser;
        }
    } else {
        goto loser;
    }

    safeBag->arena = p12ctxt->arena;
    PORT_ArenaUnmark(p12ctxt->arena, mark);

    return safeBag;

loser:
    if (mark) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
    }

    return NULL;
}

/* Creates a new certificate bag and returns a pointer to it.  If an error
 * occurs NULL is returned.
 */
sec_PKCS12CertBag *
sec_PKCS12NewCertBag(PLArenaPool *arena, SECOidTag certType)
{
    sec_PKCS12CertBag *certBag = NULL;
    SECOidData *bagType = NULL;
    SECStatus rv;
    void *mark = NULL;

    if (!arena) {
        return NULL;
    }

    mark = PORT_ArenaMark(arena);
    certBag = (sec_PKCS12CertBag *)PORT_ArenaZAlloc(arena,
                                                    sizeof(sec_PKCS12CertBag));
    if (!certBag) {
        PORT_ArenaRelease(arena, mark);
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    bagType = SECOID_FindOIDByTag(certType);
    if (!bagType) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    rv = SECITEM_CopyItem(arena, &certBag->bagID, &bagType->oid);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    PORT_ArenaUnmark(arena, mark);
    return certBag;

loser:
    PORT_ArenaRelease(arena, mark);
    return NULL;
}

/* Creates a new CRL bag and returns a pointer to it.  If an error
 * occurs NULL is returned.
 */
sec_PKCS12CRLBag *
sec_PKCS12NewCRLBag(PLArenaPool *arena, SECOidTag crlType)
{
    sec_PKCS12CRLBag *crlBag = NULL;
    SECOidData *bagType = NULL;
    SECStatus rv;
    void *mark = NULL;

    if (!arena) {
        return NULL;
    }

    mark = PORT_ArenaMark(arena);
    crlBag = (sec_PKCS12CRLBag *)PORT_ArenaZAlloc(arena,
                                                  sizeof(sec_PKCS12CRLBag));
    if (!crlBag) {
        PORT_ArenaRelease(arena, mark);
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    bagType = SECOID_FindOIDByTag(crlType);
    if (!bagType) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    rv = SECITEM_CopyItem(arena, &crlBag->bagID, &bagType->oid);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    PORT_ArenaUnmark(arena, mark);
    return crlBag;

loser:
    PORT_ArenaRelease(arena, mark);
    return NULL;
}

/* sec_PKCS12AddAttributeToBag
 * adds an attribute to a safeBag.  currently, the only attributes supported
 * are those which are specified within PKCS 12.
 *
 *      p12ctxt - the export context
 *      safeBag - the safeBag to which attributes are appended
 *      attrType - the attribute type
 *      attrData - the attribute data
 */
SECStatus
sec_PKCS12AddAttributeToBag(SEC_PKCS12ExportContext *p12ctxt,
                            sec_PKCS12SafeBag *safeBag, SECOidTag attrType,
                            SECItem *attrData)
{
    sec_PKCS12Attribute *attribute;
    void *mark = NULL, *dummy = NULL;
    SECOidData *oiddata = NULL;
    SECItem unicodeName = { siBuffer, NULL, 0 };
    void *src = NULL;
    unsigned int nItems = 0;
    SECStatus rv;

    if (!safeBag || !p12ctxt) {
        return SECFailure;
    }

    mark = PORT_ArenaMark(safeBag->arena);

    /* allocate the attribute */
    attribute = (sec_PKCS12Attribute *)PORT_ArenaZAlloc(safeBag->arena,
                                                        sizeof(sec_PKCS12Attribute));
    if (!attribute) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* set up the attribute */
    oiddata = SECOID_FindOIDByTag(attrType);
    if (!oiddata) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }
    if (SECITEM_CopyItem(p12ctxt->arena, &attribute->attrType, &oiddata->oid) !=
        SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    nItems = 1;
    switch (attrType) {
        case SEC_OID_PKCS9_LOCAL_KEY_ID: {
            src = attrData;
            break;
        }
        case SEC_OID_PKCS9_FRIENDLY_NAME: {
            if (!sec_pkcs12_convert_item_to_unicode(p12ctxt->arena,
                                                    &unicodeName, attrData, PR_FALSE,
                                                    PR_FALSE, PR_TRUE)) {
                goto loser;
            }
            src = &unicodeName;
            break;
        }
        default:
            goto loser;
    }

    /* append the attribute to the attribute value list  */
    attribute->attrValue = (SECItem **)PORT_ArenaZAlloc(p12ctxt->arena,
                                                        ((nItems + 1) * sizeof(SECItem *)));
    if (!attribute->attrValue) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* XXX this will need to be changed if attributes requiring more than
     * one element are ever used.
     */
    attribute->attrValue[0] = (SECItem *)PORT_ArenaZAlloc(p12ctxt->arena,
                                                          sizeof(SECItem));
    if (!attribute->attrValue[0]) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }
    attribute->attrValue[1] = NULL;

    rv = SECITEM_CopyItem(p12ctxt->arena, attribute->attrValue[0],
                          (SECItem *)src);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* append the attribute to the safeBag attributes */
    if (safeBag->nAttribs) {
        dummy = PORT_ArenaGrow(p12ctxt->arena, safeBag->attribs,
                               ((safeBag->nAttribs + 1) * sizeof(sec_PKCS12Attribute *)),
                               ((safeBag->nAttribs + 2) * sizeof(sec_PKCS12Attribute *)));
        safeBag->attribs = (sec_PKCS12Attribute **)dummy;
    } else {
        safeBag->attribs = (sec_PKCS12Attribute **)PORT_ArenaZAlloc(p12ctxt->arena,
                                                                    2 * sizeof(sec_PKCS12Attribute *));
        dummy = safeBag->attribs;
    }
    if (!dummy) {
        goto loser;
    }

    safeBag->attribs[safeBag->nAttribs] = attribute;
    safeBag->attribs[++safeBag->nAttribs] = NULL;

    PORT_ArenaUnmark(p12ctxt->arena, mark);
    return SECSuccess;

loser:
    if (mark) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
    }

    return SECFailure;
}

/* SEC_PKCS12AddCert
 *      Adds a certificate to the data being exported.
 *
 *      p12ctxt - the export context
 *      safe - the safeInfo to which the certificate is placed
 *      nestedDest - if the cert is to be placed within a nested safeContents then,
 *                   this value is to be specified with the destination
 *      cert - the cert to export
 *      certDb - the certificate database handle
 *      keyId - a unique identifier to associate a certificate/key pair
 *      includeCertChain - PR_TRUE if the certificate chain is to be included.
 */
SECStatus
SEC_PKCS12AddCert(SEC_PKCS12ExportContext *p12ctxt, SEC_PKCS12SafeInfo *safe,
                  void *nestedDest, CERTCertificate *cert,
                  CERTCertDBHandle *certDb, SECItem *keyId,
                  PRBool includeCertChain)
{
    sec_PKCS12CertBag *certBag;
    sec_PKCS12SafeBag *safeBag;
    void *mark;
    SECStatus rv;
    SECItem nick = { siBuffer, NULL, 0 };

    if (!p12ctxt || !cert) {
        return SECFailure;
    }
    mark = PORT_ArenaMark(p12ctxt->arena);

    /* allocate the cert bag */
    certBag = sec_PKCS12NewCertBag(p12ctxt->arena,
                                   SEC_OID_PKCS9_X509_CERT);
    if (!certBag) {
        goto loser;
    }

    if (SECITEM_CopyItem(p12ctxt->arena, &certBag->value.x509Cert,
                         &cert->derCert) != SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* if the cert chain is to be included, we should only be exporting
     * the cert from our internal database.
     */
    if (includeCertChain) {
        CERTCertificateList *certList = CERT_CertChainFromCert(cert,
                                                               certUsageSSLClient,
                                                               PR_TRUE);
        unsigned int count = 0;
        if (!certList) {
            PORT_SetError(SEC_ERROR_NO_MEMORY);
            goto loser;
        }

        /* add cert chain */
        for (count = 0; count < (unsigned int)certList->len; count++) {
            if (SECITEM_CompareItem(&certList->certs[count], &cert->derCert) != SECEqual) {
                CERTCertificate *tempCert;

                /* decode the certificate */
                /* XXX
                 * This was rather silly.  The chain is constructed above
                 * by finding all of the CERTCertificate's in the database.
                 * Then the chain is put into a CERTCertificateList, which only
                 * contains the DER.  Finally, the DER was decoded, and the
                 * decoded cert was sent recursively back to this function.
                 * Beyond being inefficent, this causes data loss (specifically,
                 * the nickname).  Instead, for 3.4, we'll do a lookup by the
                 * DER, which should return the cached entry.
                 */
                tempCert = CERT_FindCertByDERCert(CERT_GetDefaultCertDB(),
                                                  &certList->certs[count]);
                if (!tempCert) {
                    CERT_DestroyCertificateList(certList);
                    goto loser;
                }

                /* add the certificate */
                if (SEC_PKCS12AddCert(p12ctxt, safe, nestedDest, tempCert,
                                      certDb, NULL, PR_FALSE) != SECSuccess) {
                    CERT_DestroyCertificate(tempCert);
                    CERT_DestroyCertificateList(certList);
                    goto loser;
                }
                CERT_DestroyCertificate(tempCert);
            }
        }
        CERT_DestroyCertificateList(certList);
    }

    /* if the certificate has a nickname, we will set the friendly name
     * to that.
     */
    if (cert->nickname) {
        if (cert->slot && !PK11_IsInternal(cert->slot)) {
            /*
             * The cert is coming off of an external token,
             * let's strip the token name from the nickname
             * and only add what comes after the colon as the
             * nickname. -javi
             */
            char *delimit;

            delimit = PORT_Strchr(cert->nickname, ':');
            if (delimit == NULL) {
                nick.data = (unsigned char *)cert->nickname;
                nick.len = PORT_Strlen(cert->nickname);
            } else {
                delimit++;
                nick.data = (unsigned char *)PORT_ArenaStrdup(p12ctxt->arena,
                                                              delimit);
                nick.len = PORT_Strlen(delimit);
            }
        } else {
            nick.data = (unsigned char *)cert->nickname;
            nick.len = PORT_Strlen(cert->nickname);
        }
    }

    safeBag = sec_PKCS12CreateSafeBag(p12ctxt, SEC_OID_PKCS12_V1_CERT_BAG_ID,
                                      certBag);
    if (!safeBag) {
        goto loser;
    }

    /* add the friendly name and keyId attributes, if necessary */
    if (nick.data) {
        if (sec_PKCS12AddAttributeToBag(p12ctxt, safeBag,
                                        SEC_OID_PKCS9_FRIENDLY_NAME, &nick) != SECSuccess) {
            goto loser;
        }
    }

    if (keyId) {
        if (sec_PKCS12AddAttributeToBag(p12ctxt, safeBag, SEC_OID_PKCS9_LOCAL_KEY_ID,
                                        keyId) != SECSuccess) {
            goto loser;
        }
    }

    /* append the cert safeBag */
    if (nestedDest) {
        rv = sec_pkcs12_append_bag_to_safe_contents(p12ctxt->arena,
                                                    (sec_PKCS12SafeContents *)nestedDest,
                                                    safeBag);
    } else {
        rv = sec_pkcs12_append_bag(p12ctxt, safe, safeBag);
    }

    if (rv != SECSuccess) {
        goto loser;
    }

    PORT_ArenaUnmark(p12ctxt->arena, mark);
    return SECSuccess;

loser:
    if (mark) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
    }

    return SECFailure;
}

/* SEC_PKCS12AddKeyForCert
 *      Extracts the key associated with a particular certificate and exports
 *      it.
 *
 *      p12ctxt - the export context
 *      safe - the safeInfo to place the key in
 *      nestedDest - the nested safeContents to place a key
 *      cert - the certificate which the key belongs to
 *      shroudKey - encrypt the private key for export.  This value should
 *              always be true.  lower level code will not allow the export
 *              of unencrypted private keys.
 *      algorithm - the algorithm with which to encrypt the private key
 *      pwitem - the password to encrypt the private key with
 *      keyId - the keyID attribute
 *      nickName - the nickname attribute
 */
SECStatus
SEC_PKCS12AddKeyForCert(SEC_PKCS12ExportContext *p12ctxt, SEC_PKCS12SafeInfo *safe,
                        void *nestedDest, CERTCertificate *cert,
                        PRBool shroudKey, SECOidTag algorithm, SECItem *pwitem,
                        SECItem *keyId, SECItem *nickName)
{
    void *mark;
    void *keyItem;
    SECOidTag keyType;
    SECStatus rv = SECFailure;
    SECItem nickname = { siBuffer, NULL, 0 }, uniPwitem = { siBuffer, NULL, 0 };
    sec_PKCS12SafeBag *returnBag;

    if (!p12ctxt || !cert || !safe) {
        return SECFailure;
    }

    mark = PORT_ArenaMark(p12ctxt->arena);

    /* retrieve the key based upon the type that it is and
     * specify the type of safeBag to store the key in
     */
    if (!shroudKey) {

        /* extract the key unencrypted.  this will most likely go away */
        SECKEYPrivateKeyInfo *pki = PK11_ExportPrivateKeyInfo(cert,
                                                              p12ctxt->wincx);
        if (!pki) {
            PORT_ArenaRelease(p12ctxt->arena, mark);
            PORT_SetError(SEC_ERROR_PKCS12_UNABLE_TO_EXPORT_KEY);
            return SECFailure;
        }
        keyItem = PORT_ArenaZAlloc(p12ctxt->arena, sizeof(SECKEYPrivateKeyInfo));
        if (!keyItem) {
            PORT_SetError(SEC_ERROR_NO_MEMORY);
            goto loser;
        }
        rv = SECKEY_CopyPrivateKeyInfo(p12ctxt->arena,
                                       (SECKEYPrivateKeyInfo *)keyItem, pki);
        keyType = SEC_OID_PKCS12_V1_KEY_BAG_ID;
        SECKEY_DestroyPrivateKeyInfo(pki, PR_TRUE);
    } else {

        /* extract the key encrypted */
        SECKEYEncryptedPrivateKeyInfo *epki = NULL;
        PK11SlotInfo *slot = NULL;

        if (!sec_pkcs12_convert_item_to_unicode(p12ctxt->arena, &uniPwitem,
                                                pwitem, PR_TRUE, PR_TRUE, PR_TRUE)) {
            PORT_SetError(SEC_ERROR_NO_MEMORY);
            goto loser;
        }

        /* we want to make sure to take the key out of the key slot */
        if (PK11_IsInternal(p12ctxt->slot)) {
            slot = PK11_GetInternalKeySlot();
        } else {
            slot = PK11_ReferenceSlot(p12ctxt->slot);
        }

        epki = PK11_ExportEncryptedPrivateKeyInfo(slot, algorithm,
                                                  &uniPwitem, cert,
                                                  NSS_PBE_DEFAULT_ITERATION_COUNT,
                                                  p12ctxt->wincx);
        PK11_FreeSlot(slot);
        if (!epki) {
            PORT_SetError(SEC_ERROR_PKCS12_UNABLE_TO_EXPORT_KEY);
            goto loser;
        }

        keyItem = PORT_ArenaZAlloc(p12ctxt->arena,
                                   sizeof(SECKEYEncryptedPrivateKeyInfo));
        if (!keyItem) {
            PORT_SetError(SEC_ERROR_NO_MEMORY);
            goto loser;
        }
        rv = SECKEY_CopyEncryptedPrivateKeyInfo(p12ctxt->arena,
                                                (SECKEYEncryptedPrivateKeyInfo *)keyItem,
                                                epki);
        keyType = SEC_OID_PKCS12_V1_PKCS8_SHROUDED_KEY_BAG_ID;
        SECKEY_DestroyEncryptedPrivateKeyInfo(epki, PR_TRUE);
    }

    if (rv != SECSuccess) {
        goto loser;
    }

    /* if no nickname specified, let's see if the certificate has a
     * nickname.
     */
    if (!nickName) {
        if (cert->nickname) {
            nickname.data = (unsigned char *)cert->nickname;
            nickname.len = PORT_Strlen(cert->nickname);
            nickName = &nickname;
        }
    }

    /* create the safe bag and set any attributes */
    returnBag = sec_PKCS12CreateSafeBag(p12ctxt, keyType, keyItem);
    if (!returnBag) {
        rv = SECFailure;
        goto loser;
    }

    if (nickName) {
        if (sec_PKCS12AddAttributeToBag(p12ctxt, returnBag,
                                        SEC_OID_PKCS9_FRIENDLY_NAME, nickName) != SECSuccess) {
            goto loser;
        }
    }

    if (keyId) {
        if (sec_PKCS12AddAttributeToBag(p12ctxt, returnBag, SEC_OID_PKCS9_LOCAL_KEY_ID,
                                        keyId) != SECSuccess) {
            goto loser;
        }
    }

    if (nestedDest) {
        rv = sec_pkcs12_append_bag_to_safe_contents(p12ctxt->arena,
                                                    (sec_PKCS12SafeContents *)nestedDest,
                                                    returnBag);
    } else {
        rv = sec_pkcs12_append_bag(p12ctxt, safe, returnBag);
    }

loser:

    if (rv != SECSuccess) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
    } else {
        PORT_ArenaUnmark(p12ctxt->arena, mark);
    }

    return rv;
}

/* SEC_PKCS12AddCertOrChainAndKey
 *      Add a certificate and key pair to be exported.
 *
 *      p12ctxt          - the export context
 *      certSafe         - the safeInfo where the cert is stored
 *      certNestedDest   - the nested safeContents to store the cert
 *      keySafe          - the safeInfo where the key is stored
 *      keyNestedDest    - the nested safeContents to store the key
 *      shroudKey        - extract the private key encrypted?
 *      pwitem           - the password with which the key is encrypted
 *      algorithm        - the algorithm with which the key is encrypted
 *      includeCertChain - also add certs from chain to bag.
 */
SECStatus
SEC_PKCS12AddCertOrChainAndKey(SEC_PKCS12ExportContext *p12ctxt,
                               void *certSafe, void *certNestedDest,
                               CERTCertificate *cert, CERTCertDBHandle *certDb,
                               void *keySafe, void *keyNestedDest,
                               PRBool shroudKey, SECItem *pwitem,
                               SECOidTag algorithm, PRBool includeCertChain)
{
    SECStatus rv = SECFailure;
    SGNDigestInfo *digest = NULL;
    void *mark = NULL;

    if (!p12ctxt || !certSafe || !keySafe || !cert) {
        return SECFailure;
    }

    mark = PORT_ArenaMark(p12ctxt->arena);

    /* generate the thumbprint of the cert to use as a keyId */
    digest = sec_pkcs12_compute_thumbprint(&cert->derCert);
    if (!digest) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
        return SECFailure;
    }

    /* add the certificate */
    rv = SEC_PKCS12AddCert(p12ctxt, (SEC_PKCS12SafeInfo *)certSafe,
                           (SEC_PKCS12SafeInfo *)certNestedDest, cert, certDb,
                           &digest->digest, includeCertChain);
    if (rv != SECSuccess) {
        goto loser;
    }

    /* add the key */
    rv = SEC_PKCS12AddKeyForCert(p12ctxt, (SEC_PKCS12SafeInfo *)keySafe,
                                 keyNestedDest, cert,
                                 shroudKey, algorithm, pwitem,
                                 &digest->digest, NULL);
    if (rv != SECSuccess) {
        goto loser;
    }

    SGN_DestroyDigestInfo(digest);

    PORT_ArenaUnmark(p12ctxt->arena, mark);
    return SECSuccess;

loser:
    SGN_DestroyDigestInfo(digest);
    PORT_ArenaRelease(p12ctxt->arena, mark);

    return SECFailure;
}

/* like SEC_PKCS12AddCertOrChainAndKey, but always adds cert chain */
SECStatus
SEC_PKCS12AddCertAndKey(SEC_PKCS12ExportContext *p12ctxt,
                        void *certSafe, void *certNestedDest,
                        CERTCertificate *cert, CERTCertDBHandle *certDb,
                        void *keySafe, void *keyNestedDest,
                        PRBool shroudKey, SECItem *pwItem, SECOidTag algorithm)
{
    return SEC_PKCS12AddCertOrChainAndKey(p12ctxt, certSafe, certNestedDest,
                                          cert, certDb, keySafe, keyNestedDest, shroudKey, pwItem,
                                          algorithm, PR_TRUE);
}

/* SEC_PKCS12CreateNestedSafeContents
 *      Allows nesting of safe contents to be implemented.  No limit imposed on
 *      depth.
 *
 *      p12ctxt - the export context
 *      baseSafe - the base safeInfo
 *      nestedDest - a parent safeContents (?)
 */
void *
SEC_PKCS12CreateNestedSafeContents(SEC_PKCS12ExportContext *p12ctxt,
                                   void *baseSafe, void *nestedDest)
{
    sec_PKCS12SafeContents *newSafe;
    sec_PKCS12SafeBag *safeContentsBag;
    void *mark;
    SECStatus rv;

    if (!p12ctxt || !baseSafe) {
        return NULL;
    }

    mark = PORT_ArenaMark(p12ctxt->arena);

    newSafe = sec_PKCS12CreateSafeContents(p12ctxt->arena);
    if (!newSafe) {
        PORT_ArenaRelease(p12ctxt->arena, mark);
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    /* create the safeContents safeBag */
    safeContentsBag = sec_PKCS12CreateSafeBag(p12ctxt,
                                              SEC_OID_PKCS12_V1_SAFE_CONTENTS_BAG_ID,
                                              newSafe);
    if (!safeContentsBag) {
        goto loser;
    }

    /* append the safeContents to the appropriate area */
    if (nestedDest) {
        rv = sec_pkcs12_append_bag_to_safe_contents(p12ctxt->arena,
                                                    (sec_PKCS12SafeContents *)nestedDest,
                                                    safeContentsBag);
    } else {
        rv = sec_pkcs12_append_bag(p12ctxt, (SEC_PKCS12SafeInfo *)baseSafe,
                                   safeContentsBag);
    }
    if (rv != SECSuccess) {
        goto loser;
    }

    PORT_ArenaUnmark(p12ctxt->arena, mark);
    return newSafe;

loser:
    PORT_ArenaRelease(p12ctxt->arena, mark);
    return NULL;
}

/*********************************
 * Encoding routines
 *********************************/

/* Clean up the resources allocated by a sec_PKCS12EncoderContext. */
static void
sec_pkcs12_encoder_destroy_context(sec_PKCS12EncoderContext *p12enc)
{
    if (p12enc) {
        if (p12enc->outerA1ecx) {
            SEC_ASN1EncoderFinish(p12enc->outerA1ecx);
            p12enc->outerA1ecx = NULL;
        }
        if (p12enc->aSafeCinfo) {
            SEC_PKCS7DestroyContentInfo(p12enc->aSafeCinfo);
            p12enc->aSafeCinfo = NULL;
        }
        if (p12enc->middleP7ecx) {
            SEC_PKCS7EncoderFinish(p12enc->middleP7ecx, p12enc->p12exp->pwfn,
                                   p12enc->p12exp->pwfnarg);
            p12enc->middleP7ecx = NULL;
        }
        if (p12enc->middleA1ecx) {
            SEC_ASN1EncoderFinish(p12enc->middleA1ecx);
            p12enc->middleA1ecx = NULL;
        }
        if (p12enc->hmacCx) {
            PK11_DestroyContext(p12enc->hmacCx, PR_TRUE);
            p12enc->hmacCx = NULL;
        }
    }
}

/* set up the encoder context based on information in the export context
 * and return the newly allocated enocoder context.  A return of NULL
 * indicates an error occurred.
 */
static sec_PKCS12EncoderContext *
sec_pkcs12_encoder_start_context(SEC_PKCS12ExportContext *p12exp)
{
    sec_PKCS12EncoderContext *p12enc = NULL;
    unsigned int i, nonEmptyCnt;
    SECStatus rv;
    SECItem ignore = { 0 };
    void *mark;
    SECItem *salt = NULL;
    SECItem *params = NULL;

    if (!p12exp || !p12exp->safeInfos) {
        return NULL;
    }

    /* check for any empty safes and skip them */
    i = nonEmptyCnt = 0;
    while (p12exp->safeInfos[i]) {
        if (p12exp->safeInfos[i]->itemCount) {
            nonEmptyCnt++;
        }
        i++;
    }
    if (nonEmptyCnt == 0) {
        return NULL;
    }
    p12exp->authSafe.encodedSafes[nonEmptyCnt] = NULL;

    /* allocate the encoder context */
    mark = PORT_ArenaMark(p12exp->arena);
    p12enc = PORT_ArenaZNew(p12exp->arena, sec_PKCS12EncoderContext);
    if (!p12enc) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return NULL;
    }

    p12enc->arena = p12exp->arena;
    p12enc->p12exp = p12exp;

    /* set up the PFX version and information */
    PORT_Memset(&p12enc->pfx, 0, sizeof(sec_PKCS12PFXItem));
    if (!SEC_ASN1EncodeInteger(p12exp->arena, &(p12enc->pfx.version),
                               SEC_PKCS12_VERSION)) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* set up the authenticated safe content info based on the
     * type of integrity being used.  this should be changed to
     * enforce integrity mode, but will not be implemented until
     * it is confirmed that integrity must be in place
     */
    if (p12exp->integrityEnabled && !p12exp->pwdIntegrity) {
        /* create public key integrity mode */
        p12enc->aSafeCinfo = SEC_PKCS7CreateSignedData(
            p12exp->integrityInfo.pubkeyInfo.cert,
            certUsageEmailSigner,
            p12exp->integrityInfo.pubkeyInfo.certDb,
            p12exp->integrityInfo.pubkeyInfo.algorithm,
            NULL,
            p12exp->pwfn,
            p12exp->pwfnarg);
        if (!p12enc->aSafeCinfo) {
            goto loser;
        }
        if (SEC_PKCS7IncludeCertChain(p12enc->aSafeCinfo, NULL) != SECSuccess) {
            goto loser;
        }
        PORT_CheckSuccess(SEC_PKCS7AddSigningTime(p12enc->aSafeCinfo));
    } else {
        p12enc->aSafeCinfo = SEC_PKCS7CreateData();

        /* init password pased integrity mode */
        if (p12exp->integrityEnabled) {
            SECItem pwd = { siBuffer, NULL, 0 };
            PK11SymKey *symKey;
            CK_MECHANISM_TYPE integrityMechType;
            CK_MECHANISM_TYPE hmacMechType;
            salt = sec_pkcs12_generate_salt();

            /* zero out macData and set values */
            PORT_Memset(&p12enc->mac, 0, sizeof(sec_PKCS12MacData));

            if (!salt) {
                PORT_SetError(SEC_ERROR_NO_MEMORY);
                goto loser;
            }
            if (SECITEM_CopyItem(p12exp->arena, &(p12enc->mac.macSalt), salt) != SECSuccess) {
                PORT_SetError(SEC_ERROR_NO_MEMORY);
                goto loser;
            }
            if (!SEC_ASN1EncodeInteger(p12exp->arena, &(p12enc->mac.iter),
                                       NSS_PBE_DEFAULT_ITERATION_COUNT)) {
                goto loser;
            }

            /* generate HMAC key */
            if (!sec_pkcs12_convert_item_to_unicode(NULL, &pwd,
                                                    p12exp->integrityInfo.pwdInfo.password, PR_TRUE,
                                                    PR_TRUE, PR_TRUE)) {
                goto loser;
            }
            /*
             * This code only works with PKCS #12 Mac using PKCS #5 v1
             * PBA keygens. PKCS #5 v2 support will require a change to
             * the PKCS #12 spec.
             */
            params = PK11_CreatePBEParams(salt, &pwd,
                                          NSS_PBE_DEFAULT_ITERATION_COUNT);
            SECITEM_ZfreeItem(salt, PR_TRUE);
            SECITEM_ZfreeItem(&pwd, PR_FALSE);

            /* get the PBA Mechanism to generate the key */
            switch (p12exp->integrityInfo.pwdInfo.algorithm) {
                case SEC_OID_SHA1:
                    integrityMechType = CKM_PBA_SHA1_WITH_SHA1_HMAC;
                    break;
                case SEC_OID_MD5:
                    integrityMechType = CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN;
                    break;
                case SEC_OID_MD2:
                    integrityMechType = CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN;
                    break;
                default:
                    goto loser;
            }

            /* generate the key */
            symKey = PK11_KeyGen(NULL, integrityMechType, params, 20, NULL);
            PK11_DestroyPBEParams(params);
            if (!symKey) {
                goto loser;
            }

            /* initialize HMAC */
            /* Get the HMAC mechanism from the hash OID */
            hmacMechType = sec_pkcs12_algtag_to_mech(
                p12exp->integrityInfo.pwdInfo.algorithm);

            p12enc->hmacCx = PK11_CreateContextBySymKey(hmacMechType,
                                                        CKA_SIGN, symKey, &ignore);

            PK11_FreeSymKey(symKey);
            if (!p12enc->hmacCx) {
                PORT_SetError(SEC_ERROR_NO_MEMORY);
                goto loser;
            }
            rv = PK11_DigestBegin(p12enc->hmacCx);
            if (rv != SECSuccess)
                goto loser;
        }
    }

    if (!p12enc->aSafeCinfo) {
        goto loser;
    }

    PORT_ArenaUnmark(p12exp->arena, mark);

    return p12enc;

loser:
    sec_pkcs12_encoder_destroy_context(p12enc);
    if (p12exp->arena != NULL)
        PORT_ArenaRelease(p12exp->arena, mark);
    if (salt) {
        SECITEM_ZfreeItem(salt, PR_TRUE);
    }
    if (params) {
        PK11_DestroyPBEParams(params);
    }

    return NULL;
}

/* The outermost ASN.1 encoder calls this function for output.
** This function calls back to the library caller's output routine,
** which typically writes to a PKCS12 file.
 */
static void
sec_P12A1OutputCB_Outer(void *arg, const char *buf, unsigned long len,
                        int depth, SEC_ASN1EncodingPart data_kind)
{
    struct sec_pkcs12_encoder_output *output;

    output = (struct sec_pkcs12_encoder_output *)arg;
    (*output->outputfn)(output->outputarg, buf, len);
}

/* The "middle" and "inner" ASN.1 encoders call this function to output.
** This function does HMACing, if appropriate, and then buffers the data.
** The buffered data is eventually passed down to the underlying PKCS7 encoder.
 */
static void
sec_P12A1OutputCB_HmacP7Update(void *arg, const char *buf,
                               unsigned long len,
                               int depth,
                               SEC_ASN1EncodingPart data_kind)
{
    sec_pkcs12OutputBuffer *bufcx = (sec_pkcs12OutputBuffer *)arg;

    if (!buf || !len)
        return;

    if (bufcx->hmacCx) {
        PK11_DigestOp(bufcx->hmacCx, (unsigned char *)buf, len);
    }

    /* buffer */
    if (bufcx->numBytes > 0) {
        int toCopy;
        if (len + bufcx->numBytes <= bufcx->bufBytes) {
            memcpy(bufcx->buf + bufcx->numBytes, buf, len);
            bufcx->numBytes += len;
            if (bufcx->numBytes < bufcx->bufBytes)
                return;
            SEC_PKCS7EncoderUpdate(bufcx->p7eCx, bufcx->buf, bufcx->bufBytes);
            bufcx->numBytes = 0;
            return;
        }
        toCopy = bufcx->bufBytes - bufcx->numBytes;
        memcpy(bufcx->buf + bufcx->numBytes, buf, toCopy);
        SEC_PKCS7EncoderUpdate(bufcx->p7eCx, bufcx->buf, bufcx->bufBytes);
        bufcx->numBytes = 0;
        len -= toCopy;
        buf += toCopy;
    }
    /* buffer is presently empty */
    if (len >= bufcx->bufBytes) {
        /* Just pass it through */
        SEC_PKCS7EncoderUpdate(bufcx->p7eCx, buf, len);
    } else {
        /* copy it all into the buffer, and return */
        memcpy(bufcx->buf, buf, len);
        bufcx->numBytes = len;
    }
}

void
sec_FlushPkcs12OutputBuffer(sec_pkcs12OutputBuffer *bufcx)
{
    if (bufcx->numBytes > 0) {
        SEC_PKCS7EncoderUpdate(bufcx->p7eCx, bufcx->buf, bufcx->numBytes);
        bufcx->numBytes = 0;
    }
}

/* Feeds the output of a PKCS7 encoder into the next outward ASN.1 encoder.
** This function is used by both the inner and middle PCS7 encoders.
*/
static void
sec_P12P7OutputCB_CallA1Update(void *arg, const char *buf, unsigned long len)
{
    SEC_ASN1EncoderContext *cx = (SEC_ASN1EncoderContext *)arg;

    if (!buf || !len)
        return;

    SEC_ASN1EncoderUpdate(cx, buf, len);
}

/* this function encodes content infos which are part of the
 * sequence of content infos labeled AuthenticatedSafes
 */
static SECStatus
sec_pkcs12_encoder_asafe_process(sec_PKCS12EncoderContext *p12ecx)
{
    SEC_PKCS7EncoderContext *innerP7ecx;
    SEC_PKCS7ContentInfo *cinfo;
    PK11SymKey *bulkKey = NULL;
    SEC_ASN1EncoderContext *innerA1ecx = NULL;
    SECStatus rv = SECSuccess;

    if (p12ecx->currentSafe < p12ecx->p12exp->authSafe.safeCount) {
        SEC_PKCS12SafeInfo *safeInfo;
        SECOidTag cinfoType;

        safeInfo = p12ecx->p12exp->safeInfos[p12ecx->currentSafe];

        /* skip empty safes */
        if (safeInfo->itemCount == 0) {
            return SECSuccess;
        }

        cinfo = safeInfo->cinfo;
        cinfoType = SEC_PKCS7ContentType(cinfo);

        /* determine the safe type and set the appropriate argument */
        switch (cinfoType) {
            case SEC_OID_PKCS7_DATA:
            case SEC_OID_PKCS7_ENVELOPED_DATA:
                break;
            case SEC_OID_PKCS7_ENCRYPTED_DATA:
                bulkKey = safeInfo->encryptionKey;
                PK11_SetSymKeyUserData(bulkKey, &safeInfo->pwitem, NULL);
                break;
            default:
                return SECFailure;
        }

        /* start the PKCS7 encoder */
        innerP7ecx = SEC_PKCS7EncoderStart(cinfo,
                                           sec_P12P7OutputCB_CallA1Update,
                                           p12ecx->middleA1ecx, bulkKey);
        if (!innerP7ecx) {
            goto loser;
        }

        /* encode safe contents */
        p12ecx->innerBuf.p7eCx = innerP7ecx;
        p12ecx->innerBuf.hmacCx = NULL;
        p12ecx->innerBuf.numBytes = 0;
        p12ecx->innerBuf.bufBytes = sizeof p12ecx->innerBuf.buf;

        innerA1ecx = SEC_ASN1EncoderStart(safeInfo->safe,
                                          sec_PKCS12SafeContentsTemplate,
                                          sec_P12A1OutputCB_HmacP7Update,
                                          &p12ecx->innerBuf);
        if (!innerA1ecx) {
            goto loser;
        }
        rv = SEC_ASN1EncoderUpdate(innerA1ecx, NULL, 0);
        SEC_ASN1EncoderFinish(innerA1ecx);
        sec_FlushPkcs12OutputBuffer(&p12ecx->innerBuf);
        innerA1ecx = NULL;
        if (rv != SECSuccess) {
            goto loser;
        }

        /* finish up safe content info */
        rv = SEC_PKCS7EncoderFinish(innerP7ecx, p12ecx->p12exp->pwfn,
                                    p12ecx->p12exp->pwfnarg);
    }
    memset(&p12ecx->innerBuf, 0, sizeof p12ecx->innerBuf);
    return SECSuccess;

loser:
    if (innerP7ecx) {
        SEC_PKCS7EncoderFinish(innerP7ecx, p12ecx->p12exp->pwfn,
                               p12ecx->p12exp->pwfnarg);
    }

    if (innerA1ecx) {
        SEC_ASN1EncoderFinish(innerA1ecx);
    }
    memset(&p12ecx->innerBuf, 0, sizeof p12ecx->innerBuf);
    return SECFailure;
}

/* finish the HMAC and encode the macData so that it can be
 * encoded.
 */
static SECStatus
sec_Pkcs12FinishMac(sec_PKCS12EncoderContext *p12ecx)
{
    SECItem hmac = { siBuffer, NULL, 0 };
    SECStatus rv;
    SGNDigestInfo *di = NULL;
    void *dummy;

    if (!p12ecx) {
        return SECFailure;
    }

    /* make sure we are using password integrity mode */
    if (!p12ecx->p12exp->integrityEnabled) {
        return SECSuccess;
    }

    if (!p12ecx->p12exp->pwdIntegrity) {
        return SECSuccess;
    }

    /* finish the hmac */
    hmac.data = (unsigned char *)PORT_ZAlloc(SHA1_LENGTH);
    if (!hmac.data) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }

    rv = PK11_DigestFinal(p12ecx->hmacCx, hmac.data, &hmac.len, SHA1_LENGTH);

    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* create the digest info */
    di = SGN_CreateDigestInfo(p12ecx->p12exp->integrityInfo.pwdInfo.algorithm,
                              hmac.data, hmac.len);
    if (!di) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        rv = SECFailure;
        goto loser;
    }

    rv = SGN_CopyDigestInfo(p12ecx->arena, &p12ecx->mac.safeMac, di);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        goto loser;
    }

    /* encode the mac data */
    dummy = SEC_ASN1EncodeItem(p12ecx->arena, &p12ecx->pfx.encodedMacData,
                               &p12ecx->mac, sec_PKCS12MacDataTemplate);
    if (!dummy) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        rv = SECFailure;
    }

loser:
    if (di) {
        SGN_DestroyDigestInfo(di);
    }
    if (hmac.data) {
        SECITEM_ZfreeItem(&hmac, PR_FALSE);
    }
    PK11_DestroyContext(p12ecx->hmacCx, PR_TRUE);
    p12ecx->hmacCx = NULL;

    return rv;
}

/* pfx notify function for ASN1 encoder.
 * We want to stop encoding once we reach the authenticated safe.
 * At that point, the encoder will be updated via streaming
 * as the authenticated safe is  encoded.
 */
static void
sec_pkcs12_encoder_pfx_notify(void *arg, PRBool before, void *dest, int real_depth)
{
    sec_PKCS12EncoderContext *p12ecx;

    if (!before) {
        return;
    }

    /* look for authenticated safe */
    p12ecx = (sec_PKCS12EncoderContext *)arg;
    if (dest != &p12ecx->pfx.encodedAuthSafe) {
        return;
    }

    SEC_ASN1EncoderSetTakeFromBuf(p12ecx->outerA1ecx);
    SEC_ASN1EncoderSetStreaming(p12ecx->outerA1ecx);
    SEC_ASN1EncoderClearNotifyProc(p12ecx->outerA1ecx);
}

/* SEC_PKCS12Encode
 *      Encodes the PFX item and returns it to the output function, via
 *      callback.  the output function must be capable of multiple updates.
 *
 *      p12exp - the export context
 *      output - the output function callback, will be called more than once,
 *               must be able to accept streaming data.
 *      outputarg - argument for the output callback.
 */
SECStatus
SEC_PKCS12Encode(SEC_PKCS12ExportContext *p12exp,
                 SEC_PKCS12EncoderOutputCallback output, void *outputarg)
{
    sec_PKCS12EncoderContext *p12enc;
    struct sec_pkcs12_encoder_output outInfo;
    SECStatus rv;

    if (!p12exp || !output) {
        return SECFailure;
    }

    /* get the encoder context */
    p12enc = sec_pkcs12_encoder_start_context(p12exp);
    if (!p12enc) {
        return SECFailure;
    }

    outInfo.outputfn = output;
    outInfo.outputarg = outputarg;

    /* set up PFX encoder, the "outer" encoder.  Set it for streaming */
    p12enc->outerA1ecx = SEC_ASN1EncoderStart(&p12enc->pfx,
                                              sec_PKCS12PFXItemTemplate,
                                              sec_P12A1OutputCB_Outer,
                                              &outInfo);
    if (!p12enc->outerA1ecx) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        rv = SECFailure;
        goto loser;
    }
    SEC_ASN1EncoderSetStreaming(p12enc->outerA1ecx);
    SEC_ASN1EncoderSetNotifyProc(p12enc->outerA1ecx,
                                 sec_pkcs12_encoder_pfx_notify, p12enc);
    rv = SEC_ASN1EncoderUpdate(p12enc->outerA1ecx, NULL, 0);
    if (rv != SECSuccess) {
        rv = SECFailure;
        goto loser;
    }

    /* set up asafe cinfo - the output of the encoder feeds the PFX encoder */
    p12enc->middleP7ecx = SEC_PKCS7EncoderStart(p12enc->aSafeCinfo,
                                                sec_P12P7OutputCB_CallA1Update,
                                                p12enc->outerA1ecx, NULL);
    if (!p12enc->middleP7ecx) {
        rv = SECFailure;
        goto loser;
    }

    /* encode asafe */
    p12enc->middleBuf.p7eCx = p12enc->middleP7ecx;
    p12enc->middleBuf.hmacCx = NULL;
    p12enc->middleBuf.numBytes = 0;
    p12enc->middleBuf.bufBytes = sizeof p12enc->middleBuf.buf;

    /* Setup the "inner ASN.1 encoder for Authenticated Safes.  */
    if (p12enc->p12exp->integrityEnabled &&
        p12enc->p12exp->pwdIntegrity) {
        p12enc->middleBuf.hmacCx = p12enc->hmacCx;
    }
    p12enc->middleA1ecx = SEC_ASN1EncoderStart(&p12enc->p12exp->authSafe,
                                               sec_PKCS12AuthenticatedSafeTemplate,
                                               sec_P12A1OutputCB_HmacP7Update,
                                               &p12enc->middleBuf);
    if (!p12enc->middleA1ecx) {
        rv = SECFailure;
        goto loser;
    }
    SEC_ASN1EncoderSetStreaming(p12enc->middleA1ecx);
    SEC_ASN1EncoderSetTakeFromBuf(p12enc->middleA1ecx);

    /* encode each of the safes */
    while (p12enc->currentSafe != p12enc->p12exp->safeInfoCount) {
        sec_pkcs12_encoder_asafe_process(p12enc);
        p12enc->currentSafe++;
    }
    SEC_ASN1EncoderClearTakeFromBuf(p12enc->middleA1ecx);
    SEC_ASN1EncoderClearStreaming(p12enc->middleA1ecx);
    SEC_ASN1EncoderUpdate(p12enc->middleA1ecx, NULL, 0);
    SEC_ASN1EncoderFinish(p12enc->middleA1ecx);
    p12enc->middleA1ecx = NULL;

    sec_FlushPkcs12OutputBuffer(&p12enc->middleBuf);

    /* finish the encoding of the authenticated safes */
    rv = SEC_PKCS7EncoderFinish(p12enc->middleP7ecx, p12exp->pwfn,
                                p12exp->pwfnarg);
    p12enc->middleP7ecx = NULL;
    if (rv != SECSuccess) {
        goto loser;
    }

    SEC_ASN1EncoderClearTakeFromBuf(p12enc->outerA1ecx);
    SEC_ASN1EncoderClearStreaming(p12enc->outerA1ecx);

    /* update the mac, if necessary */
    rv = sec_Pkcs12FinishMac(p12enc);
    if (rv != SECSuccess) {
        goto loser;
    }

    /* finish encoding the pfx */
    rv = SEC_ASN1EncoderUpdate(p12enc->outerA1ecx, NULL, 0);

    SEC_ASN1EncoderFinish(p12enc->outerA1ecx);
    p12enc->outerA1ecx = NULL;

loser:
    sec_pkcs12_encoder_destroy_context(p12enc);
    return rv;
}

void
SEC_PKCS12DestroyExportContext(SEC_PKCS12ExportContext *p12ecx)
{
    int i = 0;

    if (!p12ecx) {
        return;
    }

    if (p12ecx->safeInfos) {
        i = 0;
        while (p12ecx->safeInfos[i] != NULL) {
            if (p12ecx->safeInfos[i]->encryptionKey) {
                PK11_FreeSymKey(p12ecx->safeInfos[i]->encryptionKey);
            }
            if (p12ecx->safeInfos[i]->cinfo) {
                SEC_PKCS7DestroyContentInfo(p12ecx->safeInfos[i]->cinfo);
            }
            i++;
        }
    }

    PK11_FreeSlot(p12ecx->slot);

    PORT_FreeArena(p12ecx->arena, PR_TRUE);
}