OpenSSL测试-随机数
-
在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务
-
使用OpenSSL定义一个私有函数 static int getRandom(char *r, int length), 获取length个字节的随机数(5‘)
-
把上述函数集成到src中的sdf.c中的SDF_GenerateRandom中(5')
-
在test中的main.c调用SDF_GenerateRandom进行测试,至少测试1个字节,5个字节,20个字节三种情况。(5‘)
-
提交代码(或代码链接)和运行结果截图
static int getRandom(char *r, int length)
{
BIGNUM *bn;
int i;
bn = BN_new(); //生成一个BIGNUM结构
//int bits = 20;
int top = -1;
int bottom = 1;
BN_rand(bn, length *8, top, bottom); //生成指定bits的随机数 uilength>是bits数= length *8,而length是字节数 = uilengh/8
char *a = BN_bn2hex(bn); //转化成16进制字符串
//puts(a);
//printf("\n");
for(i=0;*(a+i)!='\0';i++)
{
*(r+i)=*(a+i);
}
*(r+i)='\0';
BN_free(bn); //释放BIGNUM结构
return 0;
}
int SDF_GenerateRandom (void * hSessionHandle,unsigned int uiLength,unsigned char * pucRandom)
{
int k=getRandom(pucRandom,uiLength/8);
if(k==0)
printf("生成随机数成功!");
return SDR_OK;
}
#include "sdf.h"
#include <stdio.h>
#include <stdlib.h>
#include <openssl/rand.h>
int main(){
void ** pdh;
pdh = (void **) malloc(20);
int ret;
ret = SDF_OpenDevice(pdh);
if(ret != SDR_OK){
printf("error!");
} else {
printf("device opened!\n");
}
DEVICEINFO testdi;
ret = SDF_GetDeviceInfo(pdh, &testdi);
if(ret != SDR_OK){
printf("error!");
} else {
printf("Issuer Name: %s\n", testdi.IssuerName);
printf("Device Name: %s\n", testdi.DeviceName);
printf("Device Serial: %s\n", testdi.DeviceSerial);
printf("Device Version: %d\n", testdi.DeviceVersion);
}
unsigned int n;
unsigned char pRandom[10017];
scanf("%d", &n);
ret = SDF_GenerateRandom(*pdh, n, pRandom);
if(ret != SDR_OK){
printf("error!");
} else {
for(int i=0; i<n; i++)
printf("%02x", pRandom[i]);
}
printf("\n");
ret = SDF_CloseDevice(*pdh);
if(ret != SDR_OK){
printf("error!");
} else {
free(pdh);
printf("device closed!\n");
}
return 0;
}