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