struct rand_meth_st {
int (*seed) (const void *buf, int num);
int (*bytes) (unsigned char *buf, int num);
void (*cleanup) (void);
int (*add) (const void *buf, int num, double randomness);
int (*pseudorand) (unsigned char *buf, int num);
int (*status) (void);
};
实例:
#include "/usr/include/openssl/opensslconf.h"
#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/rand.h>
int main()
{
char buf[20];
char const *p;
unsigned char out[20],filename[50];
int ret,len;
BIO *print
p=RAND_file_name(filename,50);//获取随机数文件名
if(p==NULL)
{
printf("can not get rand file\n");
return -1;
}
printf("filename %s\n", filename);
ret=RAND_write_file(p); //生成一个随机数文件
len=RAND_load_file(p,1024); //将file指定的随机数文件中的数据读取bytes字节
ret=RAND_bytes(out, 20);//生成随机数,openssl根据内部维护的随机数状态来生成结果。buf用于存放生成的随机数。num为输入参数,用来指明生成随机数的字节长度;
if(ret!=1)
{
printf("err.\n");
return -1;
}
printf("rand data: \n");
for (int i = 0; i < 20; i++){
printf("%02x ", out[i]);
}
printf("\n");
RAND_cleanup();//清除函数,本函数将内部维护的随机数据清除
return 0;
}
实例:
#include "/usr/include/openssl/opensslconf.h"
#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/rand.h>
int main()
{
char buf[20];
char const *p;
unsigned char out[20],filename[50];
int ret,len;
BIO *print;
strcpy(buf,"我的随机数");
printf("strlen(buf) %ld\n", strlen(buf));//15个字节
RAND_add(buf,20,strlen(buf)); //用来计算内部随机数。其中entropy(信息熵)可以看作用户本次加入的随机数的个数, 20个字节
//Openssl给出随机数之前,用户提供的所有的随机种子数之和必须达到32字节。
strcpy(buf,"23424d");
RAND_seed(buf,20);
while(1)
{
ret=RAND_status();
if(ret==1)
{
printf("seeded enough!\n");
break;
}
else
{
printf("not enough sedded!\n");
RAND_poll();
}
}
ret=RAND_bytes(out, 20);//生成随机数,openssl根据内部维护的随机数状态来生成结果。buf用于存放生成的随机数。num为输入参数,用来指明生成随机数的字节长度;
if(ret!=1)
{
printf("err.\n");
return -1;
}
printf("rand data: \n");
for (int i = 0; i < 20; i++){
printf("%02x ", out[i]);
}
printf("\n");
RAND_cleanup();//清除函数,本函数将内部维护的随机数据清除
return 0;
}