openssl3.2 - exp - RAND_bytes_ex

文章目录

    • [openssl3.2 - exp - RAND_bytes_ex](#openssl3.2 - exp - RAND_bytes_ex)
    • 概述
    • 笔记
    • END

openssl3.2 - exp - RAND_bytes_ex

概述

生成随机数时, 要检查返回值是否成功, 不能认为一定是成功的(官方文档上有说明).

生成随机数的API, 和库上下文有关系, 使用RAND_bytes_ex()比RAND_bytes()好些.

笔记

c 复制代码
/*!
* \file main.cpp
* \note openssl3.2 - exp - RAND_bytes_ex
*/

#include "my_openSSL_lib.h"
#include <openssl/evp.h> // for EVP_MAX_BLOCK_LENGTH
#include <openssl/rand.h> // for RAND_bytes_ex

#include <cstdint> // for uint8_t

bool get_rand_buffer(uint8_t* Buf, int len);

int main(int argc, char** argv)
{
	uint8_t Buf[EVP_MAX_BLOCK_LENGTH];
	int len = (int)sizeof(Buf);

	do {
		if (!get_rand_buffer(Buf, len))
		{
			printf("error\n");
		}

		// 带缩进值打印buffer, 参数4是缩进值(打印每行之前, 先预留几个缩进空格)
		// 用BIO_dump_indent_fp打印, 能打印的好看点.
		BIO_dump_indent_fp(stdout, Buf, len, 4);

		printf("ok\n");
	} while (false);

	return 0;
}

bool get_rand_buffer(uint8_t* Buf, int len)
{
	bool b_rc = false;

	do {
		if ((NULL == Buf) || (len <= 0))
		{
			break;
		}

		// 官方文档上说, 调用RAND_bytes就行
		// 但是看了RAND_bytes()实现, 最好还是调用 RAND_bytes_ex(NULL, buf, (size_t)num, 0);, 这样能和库上下文联系起来
		// 如果在没有库上下文的场合, ctx就给NULL
		if (RAND_bytes_ex(NULL, Buf, len, 0) <= 0)
		{
			// error
			// 官方文档中特意说明, 取随机数时, 必须检查返回结果, 不要以为一定会成功
			break;
		}

		b_rc = true;
	} while (false);

	return b_rc;
}

END

相关推荐
coder4_5 天前
OpenSSL 加密算法与证书管理全解析:从基础到私有 CA 实战
https·openssl·ssl/tls·加密算法·ca证书
王小义笔记12 天前
windows电脑如何执行openssl rand命令
windows·openssl
Humbunklung15 天前
VC++ 使用OpenSSL创建RSA密钥PEM文件
开发语言·c++·openssl
深耕AI1 个月前
Win64OpenSSL-3_5_2.exe【安装步骤】
openssl
看那山瞧那水1 个月前
DELPHI 利用OpenSSL实现加解密,证书(X.509)等功能
delphi·openssl
洋哥网络科技2 个月前
openssl升级
openssl
Lazy Dave2 个月前
gmssl私钥文件格式
网络安全·ssl·openssl
沉在嵌入式的鱼3 个月前
RK3588移植Openssl库
linux·rk3588·openssl
黑屋里的马3 个月前
ssl相关命令生成证书
服务器·网络·ssl·openssl·gmssl
fangeqin3 个月前
ubuntu源码安装python3.13遇到Could not build the ssl module!解决方法
linux·python·ubuntu·openssl