2 * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
16 #include <openssl/bio.h>
17 #include <openssl/err.h>
18 #include <openssl/rand.h>
20 typedef enum OPTION_choice {
21 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
22 OPT_OUT, OPT_ENGINE, OPT_BASE64, OPT_HEX,
26 const OPTIONS rand_options[] = {
27 {OPT_HELP_STR, 1, '-', "Usage: %s [flags] num\n"},
28 {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
29 {"help", OPT_HELP, '-', "Display this summary"},
30 {"out", OPT_OUT, '>', "Output file"},
32 {"base64", OPT_BASE64, '-', "Base64 encode output"},
33 {"hex", OPT_HEX, '-', "Hex encode output"},
34 #ifndef OPENSSL_NO_ENGINE
35 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
40 int rand_main(int argc, char **argv)
44 char *outfile = NULL, *prog;
46 int format = FORMAT_BINARY, i, num = -1, r, ret = 1;
48 prog = opt_init(argc, argv, rand_options);
49 while ((o = opt_next()) != OPT_EOF) {
54 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
57 opt_help(rand_options);
64 e = setup_engine(opt_arg(), 0);
71 format = FORMAT_BASE64;
78 argc = opt_num_rest();
81 if (argc != 1 || !opt_int(argv[0], &num) || num < 0)
84 out = bio_open_default(outfile, 'w', format);
88 if (format == FORMAT_BASE64) {
89 BIO *b64 = BIO_new(BIO_f_base64());
92 out = BIO_push(b64, out);
96 unsigned char buf[4096];
100 if (chunk > (int)sizeof(buf))
102 r = RAND_bytes(buf, chunk);
105 if (format != FORMAT_TEXT) {
106 if (BIO_write(out, buf, chunk) != chunk)
109 for (i = 0; i < chunk; i++)
110 if (BIO_printf(out, "%02x", buf[i]) != 2)
115 if (format == FORMAT_TEXT)
117 if (BIO_flush(out) <= 0)
124 ERR_print_errors(bio_err);