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