#include <string.h>
#include <limits.h>
#include "apps.h"
#include <openssl/bn.h>
#include <openssl/err.h>
static struct {
int bits;
int checks;
int generate;
int hex;
int safe;
} cfg;
static const struct option prime_options[] = {
{
.name = "bits",
.argname = "n",
.desc = "Number of bits in the generated prime number",
.type = OPTION_ARG_INT,
.opt.value = &cfg.bits,
},
{
.name = "checks",
.argname = "n",
.desc = "Miller-Rabin probabilistic primality test iterations",
.type = OPTION_ARG_INT,
.opt.value = &cfg.checks,
},
{
.name = "generate",
.desc = "Generate a pseudo-random prime number",
.type = OPTION_FLAG,
.opt.flag = &cfg.generate,
},
{
.name = "hex",
.desc = "Hexadecimal prime numbers",
.type = OPTION_FLAG,
.opt.flag = &cfg.hex,
},
{
.name = "safe",
.desc = "Generate only \"safe\" prime numbers",
.type = OPTION_FLAG,
.opt.flag = &cfg.safe,
},
{NULL},
};
static void
prime_usage(void)
{
fprintf(stderr,
"usage: prime [-bits n] [-checks n] [-generate] [-hex] [-safe] "
"p\n");
options_usage(prime_options);
}
int
prime_main(int argc, char **argv)
{
BIGNUM *bn = NULL;
char *prime = NULL;
BIO *bio_out;
char *s;
int is_prime, ret = 1;
if (pledge("stdio rpath", NULL) == -1) {
perror("pledge");
exit(1);
}
memset(&cfg, 0, sizeof(cfg));
cfg.checks = 20;
if (options_parse(argc, argv, prime_options, &prime, NULL) != 0) {
prime_usage();
return (1);
}
if (prime == NULL && cfg.generate == 0) {
BIO_printf(bio_err, "No prime specified.\n");
prime_usage();
return (1);
}
if ((bio_out = BIO_new(BIO_s_file())) == NULL) {
ERR_print_errors(bio_err);
return (1);
}
BIO_set_fp(bio_out, stdout, BIO_NOCLOSE);
if (cfg.generate != 0) {
if (cfg.bits == 0) {
BIO_printf(bio_err, "Specify the number of bits.\n");
goto end;
}
bn = BN_new();
if (!bn) {
BIO_printf(bio_err, "Out of memory.\n");
goto end;
}
if (!BN_generate_prime_ex(bn, cfg.bits,
cfg.safe, NULL, NULL, NULL)) {
BIO_printf(bio_err, "Prime generation error.\n");
goto end;
}
s = cfg.hex ? BN_bn2hex(bn) : BN_bn2dec(bn);
if (s == NULL) {
BIO_printf(bio_err, "Out of memory.\n");
goto end;
}
BIO_printf(bio_out, "%s\n", s);
free(s);
} else {
if (cfg.hex) {
if (!BN_hex2bn(&bn, prime)) {
BIO_printf(bio_err, "%s is an invalid hex "
"value.\n", prime);
goto end;
}
} else {
if (!BN_dec2bn(&bn, prime)) {
BIO_printf(bio_err, "%s is an invalid decimal "
"value.\n", prime);
goto end;
}
}
is_prime = BN_is_prime_ex(bn, cfg.checks, NULL, NULL);
if (is_prime < 0) {
BIO_printf(bio_err, "BN_is_prime_ex failed.\n");
goto end;
}
BIO_printf(bio_out, "%s is %sprime\n", prime,
is_prime == 1 ? "" : "not ");
}
ret = 0;
end:
BN_free(bn);
BIO_free_all(bio_out);
return (ret);
}