1/*
2 * Decode P12 PFX using P12Coder, reencode to file
3 */
4
5#include <security_pkcs12/pkcs12Coder.h>
6#include <stdlib.h>
7#include <stdio.h>
8#include <Security/cssmtype.h>
9#include <security_cdsa_utils/cuPrintCert.h>
10#include <security_cdsa_utils/cuFileIo.h>
11
12/* decode --> encode */
13int p12Reencode(
14	const CSSM_DATA &pfx,
15	CSSM_CSP_HANDLE cspHand,
16	CFStringRef pwd,			// explicit passphrase, mutually exclusive with...
17	bool verbose,
18	unsigned loops)
19{
20	int 			ourRtn;
21
22	for(unsigned loop=0; loop<loops; loop++) {
23		{
24			/* localize scope of coder for malloc test */
25			P12Coder coder;
26			CFDataRef cfd = CFDataCreate(NULL, pfx.Data, pfx.Length);
27			ourRtn = 0;
28
29			printf("...decoding...\n");
30			try {
31				coder.setCsp(cspHand);
32				coder.setMacPassPhrase(pwd);
33				coder.decode(cfd);
34			}
35			catch(...) {
36				printf("***decode error\n");
37				return 1;
38			}
39			CFRelease(cfd);
40
41			/* should just be able to re-encode it */
42			printf("...encoding...\n");
43			CFDataRef encPfx;
44			try {
45				coder.encode(&encPfx);
46			}
47			catch(...) {
48				printf("***encode error\n");
49				return 1;
50			}
51			writeFile("encoded.p12", CFDataGetBytePtr(encPfx),
52				CFDataGetLength(encPfx));
53			printf("...wrote %u bytes to encoded.p12\n",
54				(unsigned)CFDataGetLength(encPfx));
55			CFRelease(encPfx);
56		}
57		if(loops > 1) {
58			fpurge(stdin);
59			printf("CR to continue: ");
60			getchar();
61		}
62		if(ourRtn) {
63			return ourRtn;
64		}
65	}
66	return ourRtn;
67}
68