]> git.ipfire.org Git - thirdparty/openssl.git/blame - apps/rand.c
Make V_ASN1_APP_CHOOSE work again.
[thirdparty/openssl.git] / apps / rand.c
CommitLineData
27b78273
BM
1/* apps/rand.c */
2
3#include "apps.h"
4
5#include <ctype.h>
6#include <stdio.h>
7
8#include <openssl/bio.h>
9#include <openssl/err.h>
10#include <openssl/rand.h>
11
12#undef PROG
13#define PROG rand_main
14
15/* -out file - write to file
16 * -rand file:file - PRNG seed files
17 * -base64 - encode output
18 * num - write 'num' bytes
19 */
20
21int MAIN(int, char **);
22
23int MAIN(int argc, char **argv)
24 {
25 int i, r, ret = 1;
26 int badopt;
27 char *outfile = NULL;
28 char *inrand = NULL;
29 int base64 = 0;
30 BIO *out = NULL;
31 int num = -1;
32
33 apps_startup();
34
35 if (bio_err == NULL)
36 if ((bio_err = BIO_new(BIO_s_file())) != NULL)
37 BIO_set_fp(bio_err, stderr, BIO_NOCLOSE|BIO_FP_TEXT);
38
39 badopt = 0;
40 i = 0;
41 while (!badopt && argv[++i] != NULL)
42 {
43 if (strcmp(argv[i], "-out") == 0)
44 {
45 if ((argv[i+1] != NULL) && (outfile == NULL))
46 outfile = argv[++i];
47 else
48 badopt = 1;
49 }
50 else if (strcmp(argv[i], "-rand") == 0)
51 {
52 if ((argv[i+1] != NULL) && (inrand == NULL))
53 inrand = argv[++i];
54 else
55 badopt = 1;
56 }
57 else if (strcmp(argv[i], "-base64") == 0)
58 {
59 if (!base64)
60 base64 = 1;
61 else
62 badopt = 1;
63 }
64 else if (isdigit(argv[i][0]))
65 {
66 if (num < 0)
67 {
68 r = sscanf(argv[i], "%d", &num);
69 if (r == 0 || num < 0)
70 badopt = 1;
71 }
72 else
73 badopt = 1;
74 }
75 else
76 badopt = 1;
77 }
78
79 if (num < 0)
80 badopt = 1;
81
82 if (badopt)
83 {
84 BIO_printf(bio_err, "Usage: rand [options] num\n");
85 BIO_printf(bio_err, "where options are\n");
86 BIO_printf(bio_err, "-out file - write to file\n");
afbd0746 87 BIO_printf(bio_err, "-rand file%cfile%c... - seed PRNG from files\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
27b78273
BM
88 BIO_printf(bio_err, "-base64 - encode output\n");
89 goto err;
90 }
91
92 app_RAND_load_file(NULL, bio_err, (inrand != NULL));
93 if (inrand != NULL)
94 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
95 app_RAND_load_files(inrand));
96
97 out = BIO_new(BIO_s_file());
98 if (out == NULL)
99 goto err;
100 if (outfile != NULL)
101 r = BIO_write_filename(out, outfile);
102 else
103 r = BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
104 if (r <= 0)
105 goto err;
106
107 if (base64)
108 {
109 BIO *b64 = BIO_new(BIO_f_base64());
110 if (b64 == NULL)
111 goto err;
112 out = BIO_push(b64, out);
113 }
114
115 while (num > 0)
116 {
117 unsigned char buf[4096];
118 int chunk;
119
120 chunk = num;
121 if (chunk > sizeof buf)
122 chunk = sizeof buf;
123 r = RAND_bytes(buf, chunk);
124 if (r <= 0)
125 goto err;
126 BIO_write(out, buf, chunk);
127 num -= chunk;
128 }
129 BIO_flush(out);
130
131 app_RAND_write_file(NULL, bio_err);
132 ret = 0;
133
134err:
135 ERR_print_errors(bio_err);
136 if (out)
137 BIO_free_all(out);
138 EXIT(ret);
139 }