2
0

pkread.c 1.6 KB

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