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

相关推荐
蜡台4 天前
本机 局域网 搭建本地 HTTPS 域名完整方案
网络协议·http·https·openssl
qetfw5 天前
Debian OpenSSL CA 证书配置参考:根证书、服务证书与验证
linux·debian·ssl·openssl
qetfw8 天前
Debian OpenSSL 搭建 CA 证书服务:签发、吊销与客户端信任
linux·debian·openssl·ca
smaller_maple2 个月前
T113开启openssh
openssl·openssh·t113开启ssh
dling85 个月前
OpenSSL和keytool的区别?如何使用?
openssl·keytool
鹏大师运维6 个月前
统信 UOS OpenSSL 漏洞如何修复?外网 / 内网两种方式一次讲清
linux·运维·openssl·国产操作系统·统信uos·麒麟桌面操作系统·补丁修复
小麻侬6 个月前
CMake gui构建libcurl,MTD/MT,支持openssl
openssl·libcurl·cmake gui
前进的程序员6 个月前
OpenSSL加解密原理及使用方法详解
ssl·加解密·openssl
y1233447788997 个月前
国密算法SM2实现(Openssl)
开发语言·openssl·国密
EniacCheng7 个月前
【OpenSSL】- Ubuntu22.04手动编译安装openssl
openssl