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

相关推荐
cooldream20092 天前
升级 OpenSSL 的详细步骤(解决 SSH 漏洞的前提)
运维·ssh·openssl
年薪丰厚2 天前
如何手动安装libcrypto.so.10和libssl.so.10这两个库?
openssl·libcrypto.so.10·libssl.so.10
恋喵大鲤鱼15 天前
openssl(1) command
openssl
pzs022118 天前
openssl的使用
openssl
小亦小亦_空中接力21 天前
openssl+keepalived安装部署
openssl·keepalived
摸鱼手会滑22 天前
源码编译安装python3.12没有ssl模块,python3.12 ModuleNotFoundError: No module named ‘_ssl‘
ssl·openssl·python3
老朱自强不息1 个月前
Windows 平台编译openssl3.3
windows·openssl
promise5242 个月前
openssl 详解
linux·运维·服务器·网络协议·安全·https·openssl
俱会一处2 个月前
用openssl 创建自签名证书用于内网HTTPS
https·openssl·内网·局域网
xiaogengtongxu2 个月前
CA证书和openssl介绍
网络·安全·openssl