]> git.saurik.com Git - apple/security.git/blob - SecurityTests/clxutils/keyFromCert/keyFromCert.cpp
Security-57031.1.35.tar.gz
[apple/security.git] / SecurityTests / clxutils / keyFromCert / keyFromCert.cpp
1 /*
2 * keyFromCert.cpp - extract public key from a cert.
3 */
4 #include <utilLib/common.h>
5 #include <utilLib/cspwrap.h>
6 #include <security_cdsa_utils/cuFileIo.h>
7 #include <clAppUtils/clutils.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <Security/cssm.h>
12 #include <Security/x509defs.h>
13 #include <Security/oidsattr.h>
14 #include <Security/oidscert.h>
15 #include <string.h>
16
17 static void usage(char **argv)
18 {
19 printf("Usage: %s [-q] certFile keyFile\n", argv[0]);
20 exit(1);
21 }
22
23 int main(int argc, char **argv)
24 {
25 CSSM_DATA rawCert;
26 CSSM_KEY_PTR pubKey;
27 int rtn;
28 CSSM_CL_HANDLE clHand; // CL handle
29 CSSM_RETURN crtn;
30 bool quiet = false;
31
32 const char *certFile = NULL;
33 const char *keyFile = NULL;
34
35 switch(argc) {
36 case 3:
37 certFile = argv[1];
38 keyFile = argv[2];
39 break;
40 case 4:
41 if(!strcmp(argv[1], "-q")) {
42 quiet = true;
43 certFile = argv[2];
44 keyFile = argv[3];
45 }
46 else {
47 usage(argv);
48 }
49 break;
50 default:
51 usage(argv);
52 }
53
54 unsigned len;
55 rtn = readFile(certFile, &rawCert.Data, &len);
56 if(rtn) {
57 printf("Error reading %s; %s\n", certFile, strerror(rtn));
58 exit(1);
59 }
60 rawCert.Length = len;
61 clHand = clStartup();
62 if(clHand == 0) {
63 return 0;
64 }
65 crtn = CSSM_CL_CertGetKeyInfo(clHand, &rawCert, &pubKey);
66 if(crtn) {
67 printError("CSSM_CL_CertGetKeyInfo", crtn);
68 exit(1);
69 }
70 rtn = writeFile(keyFile, pubKey->KeyData.Data, pubKey->KeyData.Length);
71 if(!quiet & (rtn == 0)) {
72 printf("...wrote %u key bytes to %s\n", (unsigned)pubKey->KeyData.Length,
73 keyFile);
74 }
75 return 0;
76 }
77