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