Created
December 13, 2019 17:57
-
-
Save kazkansouh/3931ae7654cbb3e85c751db30277a315 to your computer and use it in GitHub Desktop.
Command line app to call openssl primality check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Copyright (C) 2019 Karim Kanso. All Rights Reserved. | |
* | |
* This program is free software: you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation, either version 3 of the License, or | |
* (at your option) any later version. | |
* | |
* This program is distributed in the hope that it will be useful, | |
* but WITHOUT ANY WARRANTY; without even the implied warranty of | |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
* GNU General Public License for more details. | |
* | |
* You should have received a copy of the GNU General Public License | |
* along with this program. If not, see <http://www.gnu.org/licenses/>. | |
*/ | |
/* Trivial program to call the openssl primality check from the | |
* command line. | |
* | |
* Usage, pass prime number to test as first parameter on command | |
* line. | |
* | |
* Exit code: | |
* 2 - Error | |
* 1 - Is Prime | |
* 0 - Not Prime | |
* | |
* Compile: | |
* gcc -Wall -Wpedantic -c prime-test.c -o prime-test.o | |
* gcc prime-test.o -lcrypto -o prime-test | |
*/ | |
#include <stdio.h> | |
#include <string.h> | |
#include <openssl/bn.h> | |
int main(int argc, char** argv) { | |
if (argc != 2) { | |
fputs("usage: provide the prime number as sole argument\n", stderr); | |
return 1; | |
} | |
int i_ret = 2; | |
BIGNUM *p_bn = BN_new(); | |
BN_CTX *p_bn_ctx = BN_CTX_new(); | |
if (BN_dec2bn(&p_bn, argv[1]) != strlen(argv[1])) { | |
fputs("bad integer\n", stderr); | |
goto cleanup; | |
} | |
int i_bits = BN_num_bits(p_bn); | |
switch (BN_is_prime_ex(p_bn, i_bits / 2, p_bn_ctx, NULL)) { | |
case -1: | |
fputs("prime check failed\n", stderr); | |
break; | |
case 1: | |
fputs("is prime\n", stdout); | |
i_ret = 0; | |
break; | |
case 0: | |
fputs("not prime\n", stdout); | |
i_ret = 1; | |
break; | |
default: | |
fputs("internal error\n", stderr); | |
break; | |
} | |
cleanup: | |
BN_free(p_bn); | |
p_bn = NULL; | |
BN_CTX_free(p_bn_ctx); | |
p_bn_ctx = NULL; | |
return i_ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment