赞
踩
通过对openssl RAND_METHOD结构体进行重新赋值并导入到引擎中,在使用openssl与rand相关的算法中都会调用引擎中的rand算法
#ifndef __RANG_ENG_H__
#define __RANG_ENG_H__
#include <openssl/engine.h>
#include <stdio.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/ecdh.h>
#include <openssl/crypto.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/ssl.h>
const char *eng_id="randeng";
const char *eng_name="rand engines for OpenSSL";
#endif // DEBUG
#include "rangeng.h"
static int myrand_init(ENGINE *e)
{
printf("myrand_init\n");
return 1;
}
static int myrand_finish(ENGINE *e)
{
printf("myrand_finish\n");
return 1;
}
static int myrand_destroy(ENGINE *e)
{
printf("myrand_destroy\n");
return 1;
}
static int myrand_status(void)
{
printf("myrand_status\n");
return 1;
}
static int myrand_bytes(unsigned char *buf, size_t num)
{
printf("myrand_bytes 产生随机数%d个\n",num);
memset(buf,0,num);
return 1;
}
const RAND_METHOD rand_method=
{
NULL,
myrand_bytes,
NULL,
NULL,
NULL,
myrand_status
};
/*绑定函数*/
static int bind_pp(ENGINE *e)
{
if(!ENGINE_set_id(e,eng_id)||
!ENGINE_set_name(e,eng_name)||
!ENGINE_set_RAND(e,&rand_method)||
!ENGINE_set_destroy_function(e,myrand_destroy)||
!ENGINE_set_init_function(e,myrand_init)||
!ENGINE_set_finish_function(e,myrand_finish))
return 0;
printf("ERR_load_rsa success\n");
return 1;
}
static ENGINE *enging_range(void)
{
ENGINE*e =ENGINE_new();
if(!e)
return NULL;
if(!bind_pp(e))
{
ENGINE_free(e);
return NULL;
}
return e;
}
void ENGINE_load_rand()
{
ENGINE* e=enging_range();
if(!e)
return ;
ENGINE_add(e);
ENGINE_free(e);
//ERR_add_error(e);
}
static void display_engine_list()
{
ENGINE *h;
int loop;
h = ENGINE_get_first();
loop = 0;
printf("start:\n");
while(h)
{
printf("engine %i, id = \"%s\", name = \"%s\"\n",
loop++, ENGINE_get_id(h), ENGINE_get_name(h));
h = ENGINE_get_next(h);
}
printf("end of list\n");
ENGINE_free(h);
}
int main()
{
// 初始化 OpenSSL 引擎系统
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
//加载引擎
ENGINE_load_rand();
display_engine_list();
ENGINE *e=NULL;
e=ENGINE_by_id(eng_id);
if(!e)
{
printf("err load engine failed\n");
return 0;
}
ENGINE_init(e);
printf("RAND-----BEGIN---END\n");
// 调用引擎中的随机数生成方法
ENGINE_set_default_RAND(e);
unsigned char rand_buf[6]={0};
int err = RAND_bytes(rand_buf,5);
for(int i= 0; i < 5; i++) {
printf("%x",rand_buf[i]);
}
printf("\n");
// 清理引擎资源
ENGINE_finish(e);
ENGINE_free(e);
}
gcc rangine.c -ldl -lpthread -lcrypto -lssl -o engINE
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。