在linux命令行下,输入
man BN
查看所有的关于大数运算的API接口,此处,我们只对大数的随机数生成进行简单的举例,满足大部分需求。
随机数生成的API如下所示,
#include <openssl/bn.h>
int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_rand_range(BIGNUM *rnd, BIGNUM *range);
int BN_pseudo_rand_range(BIGNUM *rnd, BIGNUM *range);
BN_rand(BIGNUM *rnd,int bits,int top,int bottom):生成一个强密码学随机函数,是一个无法预测的随机数。rnd:需要生成的随机数,bits:需要生成随机数的位数,top:为设置最高位的值,top=-1表示最高位设置为0,top=0表示最高位设置为1,top=1时,最高两位都设置成1,bottom:不为0时,可以生成奇的随机数。测试程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bn.h>
void main(){
BIGNUM *rnd;
rnd = BN_new();
int length;
char * show;
//BN_random
int bits = 80;
int top =0;
int bottom = 0;
//测试top = -1
top = -1;
bottom = 0;
BN_rand(rnd,bits,top,bottom);
length = BN_num_bits(rnd);
show = BN_bn2dec(rnd);
printf("length:%d,rnd:%s\n",length,show);
BN_free(rnd);
}
BN_pseudo_rand:每次生成相同的随机数序列,便于调试。