]>
git.ipfire.org Git - thirdparty/openssl.git/blob - apps/rand.c
2 * Copyright 1998-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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
17 #include <openssl/bio.h>
18 #include <openssl/err.h>
19 #include <openssl/rand.h>
21 typedef enum OPTION_choice
{
22 OPT_ERR
= -1, OPT_EOF
= 0, OPT_HELP
,
23 OPT_OUT
, OPT_ENGINE
, OPT_BASE64
, OPT_HEX
,
27 const OPTIONS rand_options
[] = {
28 {OPT_HELP_STR
, 1, '-', "Usage: %s [options] num\n"},
30 OPT_SECTION("General"),
31 {"help", OPT_HELP
, '-', "Display this summary"},
32 #ifndef OPENSSL_NO_ENGINE
33 {"engine", OPT_ENGINE
, 's', "Use engine, possibly a hardware device"},
36 OPT_SECTION("Output"),
37 {"out", OPT_OUT
, '>', "Output file"},
38 {"base64", OPT_BASE64
, '-', "Base64 encode output"},
39 {"hex", OPT_HEX
, '-', "Hex encode output"},
44 {"num", 0, 0, "Number of bytes to generate"},
48 int rand_main(int argc
, char **argv
)
52 char *outfile
= NULL
, *prog
;
54 int format
= FORMAT_BINARY
, i
, num
= -1, r
, ret
= 1;
56 prog
= opt_init(argc
, argv
, rand_options
);
57 while ((o
= opt_next()) != OPT_EOF
) {
62 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
65 opt_help(rand_options
);
72 e
= setup_engine(opt_arg(), 0);
79 format
= FORMAT_BASE64
;
86 argc
= opt_num_rest();
89 if (!opt_int(argv
[0], &num
) || num
<= 0)
91 } else if (argc
> 0) {
92 BIO_printf(bio_err
, "Extra arguments given.\n");
96 out
= bio_open_default(outfile
, 'w', format
);
100 if (format
== FORMAT_BASE64
) {
101 BIO
*b64
= BIO_new(BIO_f_base64());
104 out
= BIO_push(b64
, out
);
108 unsigned char buf
[4096];
112 if (chunk
> (int)sizeof(buf
))
114 r
= RAND_bytes(buf
, chunk
);
117 if (format
!= FORMAT_TEXT
) {
118 if (BIO_write(out
, buf
, chunk
) != chunk
)
121 for (i
= 0; i
< chunk
; i
++)
122 if (BIO_printf(out
, "%02x", buf
[i
]) != 2)
127 if (format
== FORMAT_TEXT
)
129 if (BIO_flush(out
) <= 0)
136 ERR_print_errors(bio_err
);