1 /* pkread.c */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <openssl/pem.h> 6 #include <openssl/err.h> 7 #include <openssl/pkcs12.h> 8 9 /* Simple PKCS#12 file reader */ 10 11 int main(int argc, char **argv) 12 { 13 FILE *fp; 14 EVP_PKEY *pkey; 15 X509 *cert; 16 STACK_OF(X509) *ca = NULL; 17 PKCS12 *p12; 18 int i; 19 if (argc != 4) { 20 fprintf(stderr, "Usage: pkread p12file password opfile\n"); 21 exit (1); 22 } 23 SSLeay_add_all_algorithms(); 24 ERR_load_crypto_strings(); 25 if (!(fp = fopen(argv[1], "rb"))) { 26 fprintf(stderr, "Error opening file %s\n", argv[1]); 27 exit(1); 28 } 29 p12 = d2i_PKCS12_fp(fp, NULL); 30 fclose (fp); 31 if (!p12) { 32 fprintf(stderr, "Error reading PKCS#12 file\n"); 33 ERR_print_errors_fp(stderr); 34 exit (1); 35 } 36 if (!PKCS12_parse(p12, argv[2], &pkey, &cert, &ca)) { 37 fprintf(stderr, "Error parsing PKCS#12 file\n"); 38 ERR_print_errors_fp(stderr); 39 exit (1); 40 } 41 PKCS12_free(p12); 42 if (!(fp = fopen(argv[3], "w"))) { 43 fprintf(stderr, "Error opening file %s\n", argv[1]); 44 exit(1); 45 } 46 if (pkey) { 47 fprintf(fp, "***Private Key***\n"); 48 PEM_write_PrivateKey(fp, pkey, NULL, NULL, 0, NULL, NULL); 49 } 50 if (cert) { 51 fprintf(fp, "***User Certificate***\n"); 52 PEM_write_X509_AUX(fp, cert); 53 } 54 if (ca && sk_num(ca)) { 55 fprintf(fp, "***Other Certificates***\n"); 56 for (i = 0; i < sk_X509_num(ca); i++) 57 PEM_write_X509_AUX(fp, sk_X509_value(ca, i)); 58 } 59 fclose(fp); 60 return 0; 61 } 62