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

相关推荐
Lazy Dave14 天前
gmssl私钥文件格式
网络安全·ssl·openssl
沉在嵌入式的鱼1 个月前
RK3588移植Openssl库
linux·rk3588·openssl
黑屋里的马1 个月前
ssl相关命令生成证书
服务器·网络·ssl·openssl·gmssl
fangeqin2 个月前
ubuntu源码安装python3.13遇到Could not build the ssl module!解决方法
linux·python·ubuntu·openssl
API开发2 个月前
苹果芯片macOS安装版Homebrew(亲测) ,一键安装node、python、vscode等,比绿色软件还干净、无污染
vscode·python·docker·nodejs·openssl·brew·homebrew
码农不惑2 个月前
Rust使用tokio(二)HTTPS相关
https·rust·web·openssl
liulilittle2 个月前
通过高级处理器硬件指令集AES-NI实现AES-256-CFB算法并通过OPENSSL加密验证算法正确性。
linux·服务器·c++·算法·安全·加密·openssl
liulilittle2 个月前
OpenSSL 的 AES-NI 支持机制
linux·运维·服务器·算法·加密·openssl·解密
liulilittle2 个月前
通过高级处理器硬件指令集AES-NI实现AES-256-CFB算法。
linux·服务器·c++·算法·安全·加密·openssl
花花少年2 个月前
Ubuntu系统下交叉编译openssl
openssl·交叉编译