sm2keygen.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright 2014-2022 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/mem.h>
  14. #include <gmssl/sm2.h>
  15. static const char *usage = "-pass str [-out pem] [-pubout pem]\n";
  16. static const char *options =
  17. "Options\n"
  18. " -pass pass Password to encrypt the private key\n"
  19. " -out pem Output password-encrypted PKCS #8 private key in PEM format\n"
  20. " -pubout pem Output public key in PEM format\n"
  21. "\n";
  22. int sm2keygen_main(int argc, char **argv)
  23. {
  24. int ret = 1;
  25. char *prog = argv[0];
  26. char *pass = NULL;
  27. char *outfile = NULL;
  28. char *puboutfile = NULL;
  29. FILE *outfp = stdout;
  30. FILE *puboutfp = stdout;
  31. SM2_KEY key;
  32. argc--;
  33. argv++;
  34. if (argc < 1) {
  35. fprintf(stderr, "usage: %s %s\n", prog, options);
  36. return 1;
  37. }
  38. while (argc > 0) {
  39. if (!strcmp(*argv, "-help")) {
  40. printf("usage: %s %s\n", prog, usage);
  41. printf("%s\n", options);
  42. ret = 0;
  43. goto end;
  44. } else if (!strcmp(*argv, "-pass")) {
  45. if (--argc < 1) goto bad;
  46. pass = *(++argv);
  47. } else if (!strcmp(*argv, "-out")) {
  48. if (--argc < 1) goto bad;
  49. outfile = *(++argv);
  50. if (!(outfp = fopen(outfile, "wb"))) {
  51. fprintf(stderr, "%s: open '%s' failure : %s\n", prog, outfile, strerror(errno));
  52. goto end;
  53. }
  54. } else if (!strcmp(*argv, "-pubout")) {
  55. if (--argc < 1) goto bad;
  56. puboutfile = *(++argv);
  57. if (!(puboutfp = fopen(puboutfile, "wb"))) {
  58. fprintf(stderr, "%s: open '%s' failure : %s\n", prog, outfile, strerror(errno));
  59. goto end;
  60. }
  61. } else {
  62. fprintf(stderr, "%s: illegal option '%s'\n", prog, *argv);
  63. goto end;
  64. bad:
  65. fprintf(stderr, "%s: `%s` option value missing\n", prog, *argv);
  66. goto end;
  67. }
  68. argc--;
  69. argv++;
  70. }
  71. if (!pass) {
  72. fprintf(stderr, "%s: `-pass` option required\n", prog);
  73. goto end;
  74. }
  75. if (sm2_key_generate(&key) != 1
  76. || sm2_private_key_info_encrypt_to_pem(&key, pass, outfp) != 1
  77. || sm2_public_key_info_to_pem(&key, puboutfp) != 1) {
  78. fprintf(stderr, "%s: inner failure\n", prog);
  79. goto end;
  80. }
  81. ret = 0;
  82. end:
  83. gmssl_secure_clear(&key, sizeof(key));
  84. if (outfile && outfp) fclose(outfp);
  85. if (puboutfile && puboutfp) fclose(puboutfp);
  86. return ret;
  87. }