]>
git.ipfire.org Git - thirdparty/openssl.git/blob - apps/prime.c
2 * Copyright 2004-2022 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
14 #include <openssl/bn.h>
16 typedef enum OPTION_choice
{
18 OPT_HEX
, OPT_GENERATE
, OPT_BITS
, OPT_SAFE
, OPT_CHECKS
,
22 static int check_num(const char *s
, const int is_hex
)
26 * It would make sense to use ossl_isxdigit and ossl_isdigit here,
27 * but ossl_ctype_check is a local symbol in libcrypto.so.
30 for (i
= 0; ('0' <= s
[i
] && s
[i
] <= '9')
31 || ('A' <= s
[i
] && s
[i
] <= 'F')
32 || ('a' <= s
[i
] && s
[i
] <= 'f'); i
++);
34 for (i
= 0; '0' <= s
[i
] && s
[i
] <= '9'; i
++);
39 const OPTIONS prime_options
[] = {
40 {OPT_HELP_STR
, 1, '-', "Usage: %s [options] [number...]\n"},
42 OPT_SECTION("General"),
43 {"help", OPT_HELP
, '-', "Display this summary"},
44 {"bits", OPT_BITS
, 'p', "Size of number in bits"},
45 {"checks", OPT_CHECKS
, 'p', "Number of checks"},
47 OPT_SECTION("Output"),
48 {"hex", OPT_HEX
, '-', "Hex output"},
49 {"generate", OPT_GENERATE
, '-', "Generate a prime"},
50 {"safe", OPT_SAFE
, '-',
51 "When used with -generate, generate a safe prime"},
56 {"number", 0, 0, "Number(s) to check for primality if not generating"},
60 int prime_main(int argc
, char **argv
)
63 int hex
= 0, generate
= 0, bits
= 0, safe
= 0, ret
= 1;
67 prog
= opt_init(argc
, argv
, prime_options
);
68 while ((o
= opt_next()) != OPT_EOF
) {
73 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
76 opt_help(prime_options
);
86 bits
= atoi(opt_arg());
92 /* ignore parameter and argument */
102 /* Optional arguments are numbers to check. */
103 if (generate
&& !opt_check_rest_arg(NULL
))
105 argc
= opt_num_rest();
107 if (!generate
&& argc
== 0) {
108 BIO_printf(bio_err
, "Missing number (s) to check\n");
116 BIO_printf(bio_err
, "Specify the number of bits.\n");
121 BIO_printf(bio_err
, "Out of memory.\n");
124 if (!BN_generate_prime_ex(bn
, bits
, safe
, NULL
, NULL
, NULL
)) {
125 BIO_printf(bio_err
, "Failed to generate prime.\n");
128 s
= hex
? BN_bn2hex(bn
) : BN_bn2dec(bn
);
130 BIO_printf(bio_err
, "Out of memory.\n");
133 BIO_printf(bio_out
, "%s\n", s
);
136 for ( ; *argv
; argv
++) {
137 int r
= check_num(argv
[0], hex
);
140 r
= hex
? BN_hex2bn(&bn
, argv
[0]) : BN_dec2bn(&bn
, argv
[0]);
143 BIO_printf(bio_err
, "Failed to process value (%s)\n", argv
[0]);
147 BN_print(bio_out
, bn
);
148 BIO_printf(bio_out
, " (%s) %s prime\n",
150 BN_check_prime(bn
, NULL
, NULL
)