openssl3.2 - exp - generate prime
/*!
* \file main.cpp
* \note exp014_gen_prime
* openssl3.2 - exp - generate prime
* 用命令行产生质数 => openssl prime -generate -bits 256 -hex -safe
* openssl源码处理主函数 prime_main()
*/
#include "my_openSSL_lib.h"
#include <openssl/crypto.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "CMemHookRec.h"
void my_openssl_app();
bool my_gen_prime(int bits, int safe, UCHAR*& pBuf, int&lenBuf);
bool bn_data_to_bio(BIGNUM* bn, BIO* bio);
int main(int argc, char** argv)
{
setvbuf(stdout, NULL, _IONBF, 0); // 清掉stdout缓存, 防止调用printf时阻塞
mem_hook();
my_openssl_app();
mem_unhook();
/*! run result
generate safe prime(256bits) below:
0000 - d8 a6 2b e1 a9 c2 42 de-f4 e1 c9 36 c6 e9 8e 7e ..+...B....6...~
0010 - a3 ec 19 03 55 dd e8 f9-17 61 7c f2 03 d4 1a 6b ....U....a|....k
free map, g_mem_hook_map.size() = 0
*/
return 0;
}
void my_openssl_app()
{
UCHAR* pBuf = NULL;
int lenBuf = 0;
bool b_rc = false;
do {
printf("generate safe prime(256bits) below:\n");
b_rc = my_gen_prime(8 * 32, 1, pBuf, lenBuf);
if (!b_rc)
{
printf("err\n");
break;
}
BIO_dump_fp(stdout, pBuf, lenBuf);
} while (false);
if (NULL != pBuf)
{
OPENSSL_free(pBuf);
pBuf = NULL;
}
}
bool my_gen_prime(int bits, int safe, UCHAR*& pBuf, int& lenBuf)
{
BIGNUM* bn = NULL;
int i_rc = 0;
bool b_rc = false;
do {
bn = BN_new();
if (NULL == bn)
{
break;
}
i_rc = BN_generate_prime_ex(bn, bits, safe, NULL, NULL, NULL);
if (1 != i_rc)
{
break;
}
lenBuf = BN_num_bytes(bn);
if (lenBuf <= 0)
{
break;
}
pBuf = (UCHAR*)OPENSSL_zalloc(lenBuf);
if (NULL == pBuf)
{
break;
}
i_rc = BN_bn2binpad(bn, pBuf, lenBuf);
if (lenBuf != i_rc)
{
break;
}
b_rc = true;
} while (false);
if (NULL != bn)
{
BN_free(bn);
bn = NULL;
}
return b_rc;
}