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

相关推荐
Lsetea1 天前
OpenSSL verify报error 20:CAfile、fullchain与本地信任链分层排查
nginx·https·ssl证书·openssl·证书链
Lsetea9 天前
证书没到期却报certificate has expired:OpenSSL定位中间证书与系统时间
运维·https·ssl证书·openssl·证书链
Lsetea9 天前
Nginx报No required SSL certificate was sent:mTLS客户端证书排查
运维·nginx·https·ssl·openssl
Lsetea11 天前
部署证书后提示“证书名称与输入不匹配”:Safari 报错的三层排查
nginx·https·safari·ssl证书·openssl
Lsetea12 天前
OpenSSL快速生成域名证书:含SAN的自签命令、验证与排错
nginx·https·ssl证书·openssl·自签证书
Lsetea15 天前
CDN换了SSL证书仍显示旧证书?按边缘节点、SNI和缓存逐层排查
https·cdn·ssl证书·openssl·tls
Lsetea17 天前
Nginx HTTPS证书域名不匹配:用SAN与SNI定位 ERR_CERT_COMMON_NAME_INVALID
nginx·https·ssl证书·openssl·tls
bosins21 天前
Windows IIS 配置本地HTTPS 全流程指南:自签名证书 + 端口绑定 + 避坑详解
powershell·openssl
Lsetea24 天前
Nginx报SSL_CTX_use_PrivateKey failed:证书与私钥不匹配怎么排查
nginx·https·ssl证书·openssl·私钥
Lsetea1 个月前
SSL证书快过期怎么自动检查:用OpenSSL checkend做7天预警与线上证书验收
https·ssl证书·openssl·systemd·证书监控