2 * Copyright 2004-2018 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
13 #include <openssl/bn.h>
15 typedef enum OPTION_choice {
16 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
17 OPT_HEX, OPT_GENERATE, OPT_BITS, OPT_SAFE, OPT_CHECKS
20 OPTIONS prime_options[] = {
21 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [number...]\n"},
22 {OPT_HELP_STR, 1, '-',
23 " number Number to check for primality\n"},
24 {"help", OPT_HELP, '-', "Display this summary"},
25 {"hex", OPT_HEX, '-', "Hex output"},
26 {"generate", OPT_GENERATE, '-', "Generate a prime"},
27 {"bits", OPT_BITS, 'p', "Size of number in bits"},
28 {"safe", OPT_SAFE, '-',
29 "When used with -generate, generate a safe prime"},
30 {"checks", OPT_CHECKS, 'p', "Number of checks"},
34 int prime_main(int argc, char **argv)
37 int hex = 0, checks = 20, generate = 0, bits = 0, safe = 0, ret = 1;
41 prog = opt_init(argc, argv, prime_options);
42 while ((o = opt_next()) != OPT_EOF) {
47 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
50 opt_help(prime_options);
60 bits = atoi(opt_arg());
66 checks = atoi(opt_arg());
70 argc = opt_num_rest();
75 BIO_printf(bio_err, "Extra arguments given.\n");
78 } else if (argc == 0) {
79 BIO_printf(bio_err, "%s: No prime specified\n", prog);
87 BIO_printf(bio_err, "Specify the number of bits.\n");
92 BIO_printf(bio_err, "Out of memory.\n");
95 if (!BN_generate_prime_ex(bn, bits, safe, NULL, NULL, NULL)) {
96 BIO_printf(bio_err, "Failed to generate prime.\n");
99 s = hex ? BN_bn2hex(bn) : BN_bn2dec(bn);
101 BIO_printf(bio_err, "Out of memory.\n");
104 BIO_printf(bio_out, "%s\n", s);
107 for ( ; *argv; argv++) {
111 r = BN_hex2bn(&bn, argv[0]);
113 r = BN_dec2bn(&bn, argv[0]);
116 BIO_printf(bio_err, "Failed to process value (%s)\n", argv[0]);
120 BN_print(bio_out, bn);
121 BIO_printf(bio_out, " (%s) %s prime\n",
123 BN_is_prime_ex(bn, checks, NULL, NULL)