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 <stdlib.h>
14 #include <string.h>
15 #include <limits.h>
16 #include <gmssl/mem.h>
17 #include <gmssl/rand.h>
18
19
20 static const char *options = "[-hex] [-rdrand] -outlen num [-out file]";
21
rand_main(int argc,char ** argv)22 int rand_main(int argc, char **argv)
23 {
24 int ret = 1;
25 char *prog = argv[0];
26 int hex = 0;
27 int rdrand = 0;
28 int outlen = 0;
29 char *outfile = NULL;
30 FILE *outfp = stdout;
31 uint8_t buf[2048];
32 int i;
33
34 argc--;
35 argv++;
36
37 if (argc < 1) {
38 fprintf(stderr, "usage: %s %s\n", prog, options);
39 return 1;
40 }
41
42 while (argc > 0) {
43 if (!strcmp(*argv, "-help")) {
44 printf("usage: %s %s\n", prog, options);
45 ret = 0;
46 goto end;
47 } else if (!strcmp(*argv, "-hex")) {
48 hex = 1;
49 } else if (!strcmp(*argv, "-rdrand")) {
50 rdrand = 1;
51 } else if (!strcmp(*argv, "-outlen")) {
52 if (--argc < 1) goto bad;
53 outlen = atoi(*(++argv));
54 if (outlen < 1 || outlen > INT_MAX) {
55 fprintf(stderr, "%s: invalid outlen\n", prog);
56 goto end;
57 }
58 } else if (!strcmp(*argv, "-out")) {
59 if (--argc < 1) goto bad;
60 outfile = *(++argv);
61 if (!(outfp = fopen(outfile, "w"))) {
62 fprintf(stderr, "%s: open '%s' failure : %s\n", prog, outfile, strerror(errno));
63 goto end;
64 }
65 } else {
66 fprintf(stderr, "%s: illegal option '%s'\n", prog, *argv);
67 goto end;
68 bad:
69 fprintf(stderr, "%s: '%s' option value missing\n", prog, *argv);
70 goto end;
71 }
72
73 argc--;
74 argv++;
75 }
76
77 if (!outlen) {
78 fprintf(stderr, "%s: option -outlen missing\n", prog);
79 goto end;
80 }
81
82 while (outlen) {
83 size_t len = outlen < sizeof(buf) ? outlen : sizeof(buf);
84
85 if (rdrand) {
86 /*
87 if (rdrand_bytes(buf, len) != 1) {
88 fprintf(stderr, "%s: inner error\n", prog);
89 goto end;
90 }
91 */
92 } else {
93 if (rand_bytes(buf, len) != 1) {
94 fprintf(stderr, "%s: inner error\n", prog);
95 goto end;
96 }
97 }
98
99 if (hex) {
100 int i;
101 for (i = 0; i < len; i++) {
102 fprintf(outfp, "%02X", buf[i]);
103 }
104 } else {
105 if (fwrite(buf, 1, len, outfp) != len) {
106 fprintf(stderr, "%s: output failure : %s\n", prog, strerror(errno));
107 goto end;
108 }
109 }
110 outlen -= len;
111 }
112 if (hex) {
113 fprintf(outfp, "\n");
114 }
115 ret = 0;
116 end:
117 gmssl_secure_clear(buf, sizeof(buf));
118 if (outfile && outfp) fclose(outfp);
119 return ret;
120 }
121