pkread.c 1.9 KB

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