sm9encrypt.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 <string.h>
  11. #include <stdlib.h>
  12. #include <gmssl/sm9.h>
  13. #include <gmssl/error.h>
  14. static const char *options = "-pubmaster file -id str [-in file] [-out file]";
  15. int sm9encrypt_main(int argc, char **argv)
  16. {
  17. int ret = 1;
  18. char *prog = argv[0];
  19. char *mpkfile = NULL;
  20. char *id = NULL;
  21. char *infile = NULL;
  22. char *outfile = NULL;
  23. FILE *mpkfp = NULL;
  24. FILE *infp = stdin;
  25. FILE *outfp = stdout;
  26. SM9_ENC_MASTER_KEY mpk;
  27. uint8_t inbuf[SM9_MAX_PLAINTEXT_SIZE];
  28. uint8_t outbuf[SM9_MAX_CIPHERTEXT_SIZE];
  29. size_t inlen, outlen = sizeof(outbuf);
  30. argc--;
  31. argv++;
  32. if (argc < 1) {
  33. fprintf(stderr, "usage: %s %s\n", prog, options);
  34. return 1;
  35. }
  36. while (argc > 0) {
  37. if (!strcmp(*argv, "-help")) {
  38. fprintf(stdout, "usage: %s %s\n", prog, options);
  39. return 0;
  40. } else if (!strcmp(*argv, "-pubmaster")) {
  41. if (--argc < 1) goto bad;
  42. mpkfile = *(++argv);
  43. if (!(mpkfp = fopen(mpkfile, "rb"))) {
  44. error_print();
  45. goto end;
  46. }
  47. } else if (!strcmp(*argv, "-id")) {
  48. if (--argc < 1) goto bad;
  49. id = *(++argv);
  50. } else if (!strcmp(*argv, "-in")) {
  51. if (--argc < 1) goto bad;
  52. infile = *(++argv);
  53. if (!(infp = fopen(infile, "rb"))) {
  54. error_print();
  55. goto end;
  56. }
  57. } else if (!strcmp(*argv, "-out")) {
  58. if (--argc < 1) goto bad;
  59. outfile = *(++argv);
  60. if (!(outfp = fopen(outfile, "wb"))) {
  61. error_print();
  62. goto end;
  63. }
  64. } else {
  65. bad:
  66. fprintf(stderr, "%s: illegal option '%s'\n", prog, *argv);
  67. return 1;
  68. }
  69. argc--;
  70. argv++;
  71. }
  72. if (!mpkfp || !id) {
  73. error_print();
  74. goto end;
  75. }
  76. if (sm9_enc_master_public_key_from_pem(&mpk, mpkfp) != 1) {
  77. error_print();
  78. return -1;
  79. }
  80. if ((inlen = fread(inbuf, 1, sizeof(inbuf), infp)) <= 0) {
  81. error_print();
  82. goto end;
  83. }
  84. if (sm9_encrypt(&mpk, id, strlen(id), inbuf, inlen, outbuf, &outlen) != 1) {
  85. error_print();
  86. goto end;
  87. }
  88. if (outlen != fwrite(outbuf, 1, outlen, outfp)) {
  89. error_print();
  90. goto end;
  91. }
  92. ret = 0;
  93. end:
  94. if (infile && infp) fclose(infp);
  95. if (outfile && outfp) fclose(outfp);
  96. if (mpkfp) fclose(mpkfp);
  97. return ret;
  98. }