certparse.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright 2014-2023 The GmSSL Project. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the License); you may
  5. * not use this file except in compliance with the License.
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. */
  9. #include <stdio.h>
  10. #include <errno.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #include <gmssl/pem.h>
  14. #include <gmssl/x509.h>
  15. static const char *options = "[-in pem] [-out file]";
  16. static char *usage =
  17. "Options\n"
  18. "\n"
  19. " [-in pem]|stdin Input certificates in PEM format.\n"
  20. " This command supports continuous multiple certificates\n"
  21. " Do not include blank line or comments between PEM data\n"
  22. " [-out file]stdout Output file\n"
  23. "\n"
  24. "Examples\n"
  25. "\n"
  26. " gmssl certparse -in certs.pem\n"
  27. "\n";
  28. int certparse_main(int argc, char **argv)
  29. {
  30. int ret = 1;
  31. char *prog = argv[0];
  32. char *infile = NULL;
  33. char *outfile = NULL;
  34. FILE *infp = stdin;
  35. FILE *outfp = stdout;
  36. uint8_t cert[18192];
  37. size_t certlen;
  38. argc--;
  39. argv++;
  40. while (argc > 0) {
  41. if (!strcmp(*argv, "-help")) {
  42. printf("usage: gmssl %s %s\n\n", prog, options);
  43. printf("%s\n", usage);
  44. goto end;
  45. } else if (!strcmp(*argv, "-in")) {
  46. if (--argc < 1) goto bad;
  47. infile = *(++argv);
  48. if (!(infp = fopen(infile, "rb"))) {
  49. fprintf(stderr, "%s: open '%s' failure : %s\n", prog, infile, strerror(errno));
  50. goto end;
  51. }
  52. } else if (!strcmp(*argv, "-out")) {
  53. if (--argc < 1) goto bad;
  54. outfile = *(++argv);
  55. if (!(outfp = fopen(outfile, "wb"))) {
  56. fprintf(stderr, "%s: open '%s' failure : %s\n", prog, outfile, strerror(errno));
  57. goto end;
  58. }
  59. } else {
  60. fprintf(stderr, "%s: illegal option `%s`\n", prog, *argv);
  61. goto end;
  62. bad:
  63. fprintf(stderr, "%s: `%s` option value missing\n", prog, *argv);
  64. goto end;
  65. }
  66. argc--;
  67. argv++;
  68. }
  69. for (;;) {
  70. int rv;
  71. if ((rv = x509_cert_from_pem(cert, &certlen, sizeof(cert), infp)) != 1) {
  72. if (rv < 0) fprintf(stderr, "%s: read certificate failure\n", prog);
  73. else ret = 0;
  74. goto end;
  75. }
  76. x509_cert_print(outfp, 0, 0, "Certificate", cert, certlen);
  77. if (x509_cert_to_pem(cert, certlen, outfp) != 1) {
  78. fprintf(stderr, "%s: output certficate failure\n", prog);
  79. goto end;
  80. }
  81. }
  82. end:
  83. if (infile && infp) fclose(infp);
  84. if (outfile && outfp) fclose(outfp);
  85. return ret;
  86. }