本专栏订阅后可查看以下文章
1、RAND随机数在OpenSSL中的使用和ENGINE算法替换
在日常工作中使用密码,就一定会接触到OpenSSL,这个算法库带给我们的东西太多太多,不管是密码算法层面,还有代码框架和使用技巧上更是值得我们去学习和专研。
从接触密码到现在,感触颇深。刚开始因为工作需要,自己学习OpenSSL和使用密码卡,作为密码界的新人,完全无处下手,OpenSSL代码又特别多,最困惑的就是函数入口在哪里?我需要包含什么头文件?怎样才能真正的调用对应的算法。所有的东西都需要从零开始,最初的代码只为了功能,毫无深度可言。现在回头来看,当时实在太年轻!
//获取
RAND_bytes(rand, randLen);
具体的调用方式,请查看下方的使用实例,添加了主要的说明信息,助于理解。
/****************************************************************
* FileName: engine_rand.c
* Author: labixiaoxin1849
* Date: 2022-07-29
* Description: replace rand algorithm call of OpenSSL
****************************************************************/
#include <openssl/engine.h>
#define ENGINE_RAND_ID "101"
static int ENGINE_RAND_status(void) {
printf("RAND_status engine test\n");
return 1;
}
static int ENGINE_RAND_bytes(unsigned char *data, int len)
{
printf("RAND_bytes engine test\n");
return 1;
}
// 随机数引擎方式与其他引擎方式不同
// 没有new方法,直接设置结构体内容
static RAND_METHOD engine_rand_meth = {
NULL, // RAND_seed 种子函数
ENGINE_RAND_bytes, // RAND_bytes 生成函数
NULL, // RAND_cleanup 状态清除函数
NULL, // RAND_add 种子添加函数
NULL, // RAND_pseudorand 可重现的随机数函数
ENGINE_RAND_status, // RAND_status 状态查询函数
};
static int lbxx_engine_rand()
{
ENGINE *e = NULL;
if ((e = ENGINE_new()) == NULL){
return 1;
}
if (!ENGINE_set_id(e, ENGINE_RAND_ID)){
ENGINE_free(e);
return 1;
}
// 无需申请内存,也无申请的方法
ENGINE_set_RAND(e, &engine_rand_meth);
if (!ENGINE_set_default(e, ENGINE_METHOD_RAND)){
ENGINE_free(e);
return 1;
}
ENGINE_free(e);
return 0;
}
int lbxx_rand_soft_test() {
unsigned char rand[256] = { 0 };
unsigned int randLen = sizeof(rand);
if (!RAND_status()){
return -1;
}
if (RAND_bytes(rand, randLen) <= 0){
return -1;
}
printf("test rand success!!!\n");
return 0;
}
int main(int argc, char *argv[]) {
if(argc >= 2){
lbxx_engine_rand();
}
lbxx_rand_soft_test();
return 0;
}