1 /* 2 * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. 3 * 4 * Licensed under the OpenSSL license (the "License"). You may not use 5 * this file except in compliance with the License. You can obtain a copy 6 * in the file LICENSE in the source distribution or at 7 * https://www.openssl.org/source/license.html 8 */ 9 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <openssl/pem.h> 13 #include <openssl/err.h> 14 #include <openssl/pkcs12.h> 15 16 /* Simple PKCS#12 file reader */ 17 18 int main(int argc, char **argv) 19 { 20 FILE *fp; 21 EVP_PKEY *pkey; 22 X509 *cert; 23 STACK_OF(X509) *ca = NULL; 24 PKCS12 *p12; 25 int i; 26 if (argc != 4) { 27 fprintf(stderr, "Usage: pkread p12file password opfile\n"); 28 exit(1); 29 } 30 OpenSSL_add_all_algorithms(); 31 ERR_load_crypto_strings(); 32 if ((fp = fopen(argv[1], "rb")) == NULL) { 33 fprintf(stderr, "Error opening file %s\n", argv[1]); 34 exit(1); 35 } 36 p12 = d2i_PKCS12_fp(fp, NULL); 37 fclose(fp); 38 if (!p12) { 39 fprintf(stderr, "Error reading PKCS#12 file\n"); 40 ERR_print_errors_fp(stderr); 41 exit(1); 42 } 43 if (!PKCS12_parse(p12, argv[2], &pkey, &cert, &ca)) { 44 fprintf(stderr, "Error parsing PKCS#12 file\n"); 45 ERR_print_errors_fp(stderr); 46 exit(1); 47 } 48 PKCS12_free(p12); 49 if ((fp = fopen(argv[3], "w")) == NULL) { 50 fprintf(stderr, "Error opening file %s\n", argv[1]); 51 exit(1); 52 } 53 if (pkey) { 54 fprintf(fp, "***Private Key***\n"); 55 PEM_write_PrivateKey(fp, pkey, NULL, NULL, 0, NULL, NULL); 56 } 57 if (cert) { 58 fprintf(fp, "***User Certificate***\n"); 59 PEM_write_X509_AUX(fp, cert); 60 } 61 if (ca && sk_X509_num(ca)) { 62 fprintf(fp, "***Other Certificates***\n"); 63 for (i = 0; i < sk_X509_num(ca); i++) 64 PEM_write_X509_AUX(fp, sk_X509_value(ca, i)); 65 } 66 fclose(fp); 67 return 0; 68 } 69