openssl3.2 - 官方demo学习 - encrypt - rsa_encrypt.c
文章目录
- openssl3.2 - 官方demo学习 - encrypt - rsa_encrypt.c
- 概述
- 笔记
- END
openssl3.2 - 官方demo学习 - encrypt - rsa_encrypt.c
概述
从内存中的DER共钥数据构造pub_key, 用公钥加密明文, 输出密文. 非对称加密
从内存中的DER私钥数据构造priv_key, 用私钥解密密文, 输出明文, 非对称解密
使用的哪种非堆成加解密算法是生成证书中指定的.
在从DER证书中构造key时, 也要指定RSA参数.
在加解密初始化, 要设置RSA相关参数
加解密之前, 都有API可以从要操作的数据长度估算出操作后的数据长度
这个例子演示了从内存中拿数据来进行非对称加解密, 避免了公钥/私钥数据落地
笔记
/*!
\file rsa_encrypt.c
\note openssl3.2 - 官方demo学习 - encrypt - rsa_encrypt.c
从内存中的DER共钥数据构造pub_key, 用公钥加密明文, 输出密文. 非对称加密
从内存中的DER私钥数据构造priv_key, 用私钥解密密文, 输出铭文, 非对称解密
使用的哪种非堆成加解密算法是生成证书中指定的.
在从DER证书中构造key时, 也要指定RSA参数.
在加解密初始化, 要设置RSA相关参数
加解密之前, 都有API可以从要操作的数据长度估算出操作后的数据长度
这个例子演示了从内存中拿数据来进行非对称加解密, 避免了公钥/私钥数据落地
*//*-* Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.** Licensed under the Apache License 2.0 (the "License"). You may not use* this file except in compliance with the License. You can obtain a copy* in the file LICENSE in the source distribution or at* https://www.openssl.org/source/license.html*//** An example that uses EVP_PKEY_encrypt and EVP_PKEY_decrypt methods* to encrypt and decrypt data using an RSA keypair.* RSA encryption produces different encrypted output each time it is run,* hence this is not a known answer test.*/#include <stdio.h>
#include <stdlib.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/decoder.h>
#include <openssl/core_names.h>
#include "rsa_encrypt.h"#include "my_openSSL_lib.h"/* Input data to encrypt */
static const unsigned char msg[] =
"To be, or not to be, that is the question,\n"
"Whether tis nobler in the minde to suffer\n"
"The slings and arrowes of outragious fortune,\n"
"Or to take Armes again in a sea of troubles";/** For do_encrypt(), load an RSA public key from pub_key_der[].* For do_decrypt(), load an RSA private key from priv_key_der[].*/
static EVP_PKEY* get_key(OSSL_LIB_CTX* libctx, const char* propq, int public)
{OSSL_DECODER_CTX* dctx = NULL;EVP_PKEY* pkey = NULL;int selection;const unsigned char* data;size_t data_len;if (public) {selection = EVP_PKEY_PUBLIC_KEY;data = g_pub_key_der;data_len = sizeof(g_pub_key_der);}else {selection = EVP_PKEY_KEYPAIR;data = g_priv_key_der;data_len = sizeof(g_priv_key_der);}dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, "RSA",selection, libctx, propq);(void)OSSL_DECODER_from_data(dctx, &data, &data_len);OSSL_DECODER_CTX_free(dctx);return pkey;
}/* Set optional parameters for RSA OAEP Padding */
static void set_optional_params(OSSL_PARAM* p, const char* propq)
{static unsigned char label[] = "label";/* "pkcs1" is used by default if the padding mode is not set */*p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_PAD_MODE,OSSL_PKEY_RSA_PAD_MODE_OAEP, 0);/* No oaep_label is used if this is not set */*p++ = OSSL_PARAM_construct_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL,label, sizeof(label));/* "SHA1" is used if this is not set */*p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST,"SHA256", 0);/** If a non default property query needs to be specified when fetching the* OAEP digest then it needs to be specified here.*/if (propq != NULL)*p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS,(char*)propq, 0);/** OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST and* OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST_PROPS can also be optionally added* here if the MGF1 digest differs from the OAEP digest.*/*p = OSSL_PARAM_construct_end();
}/** The length of the input data that can be encrypted is limited by the* RSA key length minus some additional bytes that depends on the padding mode.**/
static int do_encrypt(OSSL_LIB_CTX* libctx,const unsigned char* in, size_t in_len,unsigned char** out, size_t* out_len)
{int ret = 0, public = 1;size_t buf_len = 0;unsigned char* buf = NULL;const char* propq = NULL;EVP_PKEY_CTX* ctx = NULL;EVP_PKEY* pub_key = NULL;OSSL_PARAM params[5];/* Get public key */pub_key = get_key(libctx, propq, public);if (pub_key == NULL) {fprintf(stderr, "Get public key failed.\n");goto cleanup;}ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pub_key, propq);if (ctx == NULL) {fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed.\n");goto cleanup;}set_optional_params(params, propq);/* If no optional parameters are required then NULL can be passed */if (EVP_PKEY_encrypt_init_ex(ctx, params) <= 0) {fprintf(stderr, "EVP_PKEY_encrypt_init_ex() failed.\n");goto cleanup;}/* Calculate the size required to hold the encrypted data */if (EVP_PKEY_encrypt(ctx, NULL, &buf_len, in, in_len) <= 0) {fprintf(stderr, "EVP_PKEY_encrypt() failed.\n");goto cleanup;}buf = OPENSSL_zalloc(buf_len);if (buf == NULL) {fprintf(stderr, "Malloc failed.\n");goto cleanup;}if (EVP_PKEY_encrypt(ctx, buf, &buf_len, in, in_len) <= 0) {fprintf(stderr, "EVP_PKEY_encrypt() failed.\n");goto cleanup;}*out_len = buf_len;*out = buf;fprintf(stdout, "Encrypted:\n");BIO_dump_indent_fp(stdout, buf, (int)buf_len, 2);fprintf(stdout, "\n");ret = 1;cleanup:if (!ret)OPENSSL_free(buf);EVP_PKEY_free(pub_key);EVP_PKEY_CTX_free(ctx);return ret;
}static int do_decrypt(OSSL_LIB_CTX* libctx, const char* in, size_t in_len,unsigned char** out, size_t* out_len)
{int ret = 0, public = 0;size_t buf_len = 0;unsigned char* buf = NULL;const char* propq = NULL;EVP_PKEY_CTX* ctx = NULL;EVP_PKEY* priv_key = NULL;OSSL_PARAM params[5];/* Get private key */priv_key = get_key(libctx, propq, public);if (priv_key == NULL) {fprintf(stderr, "Get private key failed.\n");goto cleanup;}ctx = EVP_PKEY_CTX_new_from_pkey(libctx, priv_key, propq);if (ctx == NULL) {fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed.\n");goto cleanup;}/* The parameters used for encryption must also be used for decryption */set_optional_params(params, propq);/* If no optional parameters are required then NULL can be passed */if (EVP_PKEY_decrypt_init_ex(ctx, params) <= 0) {fprintf(stderr, "EVP_PKEY_decrypt_init_ex() failed.\n");goto cleanup;}/* Calculate the size required to hold the decrypted data */if (EVP_PKEY_decrypt(ctx, NULL, &buf_len, in, in_len) <= 0) {fprintf(stderr, "EVP_PKEY_decrypt() failed.\n");goto cleanup;}buf = OPENSSL_zalloc(buf_len);if (buf == NULL) {fprintf(stderr, "Malloc failed.\n");goto cleanup;}if (EVP_PKEY_decrypt(ctx, buf, &buf_len, in, in_len) <= 0) {fprintf(stderr, "EVP_PKEY_decrypt() failed.\n");goto cleanup;}*out_len = buf_len;*out = buf;fprintf(stdout, "Decrypted:\n");BIO_dump_indent_fp(stdout, buf, (int)buf_len, 2);fprintf(stdout, "\n");ret = 1;cleanup:if (!ret)OPENSSL_free(buf);EVP_PKEY_free(priv_key);EVP_PKEY_CTX_free(ctx);return ret;
}int main(void)
{int ret = EXIT_FAILURE;size_t msg_len = sizeof(msg) - 1;size_t encrypted_len = 0, decrypted_len = 0;unsigned char* encrypted = NULL, * decrypted = NULL;OSSL_LIB_CTX* libctx = NULL;if (!do_encrypt(libctx, msg, msg_len, &encrypted, &encrypted_len)) {fprintf(stderr, "encryption failed.\n");goto cleanup;}if (!do_decrypt(libctx, encrypted, encrypted_len,&decrypted, &decrypted_len)) {fprintf(stderr, "decryption failed.\n");goto cleanup;}if (CRYPTO_memcmp(msg, decrypted, decrypted_len) != 0) {fprintf(stderr, "Decrypted data does not match expected value\n");goto cleanup;}ret = EXIT_SUCCESS;cleanup:OPENSSL_free(decrypted);OPENSSL_free(encrypted);OSSL_LIB_CTX_free(libctx);if (ret != EXIT_SUCCESS)ERR_print_errors_fp(stderr);return ret;
}
END
相关文章:
openssl3.2 - 官方demo学习 - encrypt - rsa_encrypt.c
文章目录 openssl3.2 - 官方demo学习 - encrypt - rsa_encrypt.c概述笔记END openssl3.2 - 官方demo学习 - encrypt - rsa_encrypt.c 概述 从内存中的DER共钥数据构造pub_key, 用公钥加密明文, 输出密文. 非对称加密 从内存中的DER私钥数据构造priv_key, 用私钥解密密文, 输出…...
ARCGIS PRO SDK Annotation 概念及操作
使用Annotation的API功能。Annotation 的API功能位于ArcGIS.Core.dll中。Annotation API通常与地理数据库、地图创作和编辑结合使用。ArcGIS.Core.dll ArcGIS.Core.Data.map API中的几乎所有方法都应该在MCT上调用。 一、Annotation featureclass 1、从GeodatabaseGeodatabase数…...

dp专题13 零钱兑换II
本题链接:. - 力扣(LeetCode) 题目: 思路: 根据题意,这是一道很裸的背包问题,其中这里是返回 背包方案数 的。 我们可以直接推出公式 : dp [ j ] dp[ j - coins[ i ] ] 在我之前…...

el-dialog嵌套使用,只显示遮罩层的问题
直接上解决方法 <!-- 错误写法 --><el-dialog><el-dialog></el-dialog></el-dialog><!-- 正确写法 --><el-dialog></el-dialog><el-dialog></el-dialog>我是不建议嵌套使用的,平级也能调用,…...
响应式Web开发项目教程(HTML5+CSS3+Bootstrap)第2版 例3-5 CSS3 动画
代码 <!doctype html> <html> <head> <meta charset"utf-8"> <title>CSS3 动画</title> <style> .img {width: 150px; } keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg);} } img…...

一款实用的.NET Core加密解密工具类库
前言 在我们日常开发工作中,为了数据安全问题对数据加密、解密是必不可少的。加密方式有很多种如常见的AES,RSA,MD5,SAH1,SAH256,DES等,这时候假如我们有一个封装的对应加密解密工具类可以直接…...
C/C++内存布局
1. C 结构体的内存布局 以一个例子来看struct的内存结构 #define NP_FUNC_WRAPPER __attribute__((optimize(0)))struct StructBody {int first_int_placeholder;int second_int_placeholder;double third_double_placeholder; };class ClassBody {public:int first_int_place…...
springboot(ssm母婴全程服务管理系统 母婴用品服务商城Java系统
springboot(ssm母婴全程服务管理系统 母婴用品服务商城Java系统 开发语言:Java 框架:ssm/springboot vue JDK版本:JDK1.8(或11) 服务器:tomcat 数据库:mysql 5.7(或8.0…...

修改SSH默认端口,使SSH连接更安全
以CentOS7.9为例: 1、修改配置文件 vi /etc/ssh/sshd_config 2、远程电脑可连接,暂时将SELinux关闭 # 查询状态 getenforce # 关闭 setenforce 0 # 开启 setenforce 1 3、SELinux设置(如果启用),semanage管理工具安…...
React16源码: React中调度之requestWork的源码实现
requestWork 1 )概述 在 scheduleWork 中,找到了创建更新的fiber对应的root节点然后对它进行了一些操作之后,调用了 requestWork,开始请求工作在 requestWork 里面它会做哪些东西呢? 首先我们要把这个root节点加入到调…...

【白话机器学习的数学】读书笔记(3)学习分类(感知机、逻辑回归)
三、学习分类 1.分类的目的 找到一条线把白点和黑点分开。这条直线是使权重向量成为法线向量的直线。(解释见下图) 直线的表达式为: ω ⋅ x ∑ i 1 n ω i ⋅ x i 0 \omegax \sum_{i1}^n\omega_i x_i 0 ω⋅xi1∑nωi⋅xi0 ω \omega ω是权重向量权…...

书生·浦语大模型实战营-学习笔记3
目录 (3)基于 InternLM 和 LangChain 搭建你的知识库1. 大模型开发范式(RAG、Fine-tune)RAG微调 (传统自然语言处理的方法) 2. LangChain简介(RAG开发框架)3. 构建向量数据库4. 搭建知识库助手5. Web Demo部…...

MySQL下对[库]的操作
目录 创建数据库 创建一个数据库案例: 字符集和校验规则: 默认字符集: 默认校验规则: 查看数据库支持的字符集: 查看数据库支持的字符集校验规则: 校验规则对数据库的影响: 操作数据…...

Django(七)
1.靓号管理 1.1 表结构 根据表结构的需求,在models.py中创建类(由类生成数据库中的表)。 class PrettyNum(models.Model):""" 靓号表 """mobile models.CharField(verbose_name"手机号", max_len…...
AT24C02读写操作 一
//AT24C02初始化 void AT24C02_Init(void) { IIC_Init(); } //AT24C02的字节写入 写一个字节 void AT24C02_WordWrite(uint8_Address,uint8_t Data) { //1。主机发送开始信号 IIC_StartSignal(); //2.主机发送器件地址 写操作 IIC_SentBytes(0xA0); //3.主机等侍从机应…...
.NET 8 中引入新的 IHostedLifecycleService 接口 实现定时任务
在这篇文章中,我们将了解 .NET 8 中为托管服务引入的一些新生命周期事件。请注意,这篇文章与 .NET 8 相关,在撰写本文时,.NET 8 目前处于预览状态。在 11 月 .NET 8 最终版本发布之前,类型和实现可能会发生变化。要继续…...

Redis--Geo指令的语法和使用场景举例(附近的人功能)
文章目录 前言Geo介绍Geo指令使用使用场景:附近的人参考文献 前言 Redis除了常见的五种数据类型之外,其实还有一些少见的数据结构,如Geo,HyperLogLog等。虽然它们少见,但是作用却不容小觑。本文将介绍Geo指令的语法和…...
127.0.0.1和0.0.0.0的区别
在网络开发中,经常会涉及到两个特殊的IP地址:127.0.0.1和0.0.0.0。这两者之间有一些关键的区别,本文将深入介绍它们的作用和用途。 127.0.0.1 127.0.0.1 是本地回环地址,通常称为 “localhost”。作用是让网络应用程序能够与本地…...
SpringBoot ES 聚合后多字段加减乘除
SpringBoot ES 聚合后多字段加减乘除 在SpringData Elasticsearch中,聚合统计的原理主要依赖于Elasticsearch本身的聚合框架。Elasticsearch提供了强大的聚合功能,使得你可以对文档进行各种计算和统计,从而得到有关数据集的有用信息。 Elast…...
React16源码: React中requestCurrentTime和expirationTime的源码实现补充
requestCurrentTime 1 )概述 关于 currentTime,在计算 expirationTime 和其他的一些地方都会用到 从它的名义上来讲,应等于performance.now() 或者 Date.now() 就是指定的当前时间在react整体设计当中,它是有一些特定的用处和一些…...

【JavaEE】-- HTTP
1. HTTP是什么? HTTP(全称为"超文本传输协议")是一种应用非常广泛的应用层协议,HTTP是基于TCP协议的一种应用层协议。 应用层协议:是计算机网络协议栈中最高层的协议,它定义了运行在不同主机上…...

《从零掌握MIPI CSI-2: 协议精解与FPGA摄像头开发实战》-- CSI-2 协议详细解析 (一)
CSI-2 协议详细解析 (一) 1. CSI-2层定义(CSI-2 Layer Definitions) 分层结构 :CSI-2协议分为6层: 物理层(PHY Layer) : 定义电气特性、时钟机制和传输介质(导线&#…...

Python实现prophet 理论及参数优化
文章目录 Prophet理论及模型参数介绍Python代码完整实现prophet 添加外部数据进行模型优化 之前初步学习prophet的时候,写过一篇简单实现,后期随着对该模型的深入研究,本次记录涉及到prophet 的公式以及参数调优,从公式可以更直观…...

Keil 中设置 STM32 Flash 和 RAM 地址详解
文章目录 Keil 中设置 STM32 Flash 和 RAM 地址详解一、Flash 和 RAM 配置界面(Target 选项卡)1. IROM1(用于配置 Flash)2. IRAM1(用于配置 RAM)二、链接器设置界面(Linker 选项卡)1. 勾选“Use Memory Layout from Target Dialog”2. 查看链接器参数(如果没有勾选上面…...
数据链路层的主要功能是什么
数据链路层(OSI模型第2层)的核心功能是在相邻网络节点(如交换机、主机)间提供可靠的数据帧传输服务,主要职责包括: 🔑 核心功能详解: 帧封装与解封装 封装: 将网络层下发…...

SpringCloudGateway 自定义局部过滤器
场景: 将所有请求转化为同一路径请求(方便穿网配置)在请求头内标识原来路径,然后在将请求分发给不同服务 AllToOneGatewayFilterFactory import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; impor…...
CSS设置元素的宽度根据其内容自动调整
width: fit-content 是 CSS 中的一个属性值,用于设置元素的宽度根据其内容自动调整,确保宽度刚好容纳内容而不会超出。 效果对比 默认情况(width: auto): 块级元素(如 <div>)会占满父容器…...

让回归模型不再被异常值“带跑偏“,MSE和Cauchy损失函数在噪声数据环境下的实战对比
在机器学习的回归分析中,损失函数的选择对模型性能具有决定性影响。均方误差(MSE)作为经典的损失函数,在处理干净数据时表现优异,但在面对包含异常值的噪声数据时,其对大误差的二次惩罚机制往往导致模型参数…...

LLMs 系列实操科普(1)
写在前面: 本期内容我们继续 Andrej Karpathy 的《How I use LLMs》讲座内容,原视频时长 ~130 分钟,以实操演示主流的一些 LLMs 的使用,由于涉及到实操,实际上并不适合以文字整理,但还是决定尽量整理一份笔…...
MinIO Docker 部署:仅开放一个端口
MinIO Docker 部署:仅开放一个端口 在实际的服务器部署中,出于安全和管理的考虑,我们可能只能开放一个端口。MinIO 是一个高性能的对象存储服务,支持 Docker 部署,但默认情况下它需要两个端口:一个是 API 端口(用于存储和访问数据),另一个是控制台端口(用于管理界面…...