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整体设计当中,它是有一些特定的用处和一些…...
蓝桥杯 2024 15届国赛 A组 儿童节快乐
P10576 [蓝桥杯 2024 国 A] 儿童节快乐 题目描述 五彩斑斓的气球在蓝天下悠然飘荡,轻快的音乐在耳边持续回荡,小朋友们手牵着手一同畅快欢笑。在这样一片安乐祥和的氛围下,六一来了。 今天是六一儿童节,小蓝老师为了让大家在节…...
Linux简单的操作
ls ls 查看当前目录 ll 查看详细内容 ls -a 查看所有的内容 ls --help 查看方法文档 pwd pwd 查看当前路径 cd cd 转路径 cd .. 转上一级路径 cd 名 转换路径 …...
C# SqlSugar:依赖注入与仓储模式实践
C# SqlSugar:依赖注入与仓储模式实践 在 C# 的应用开发中,数据库操作是必不可少的环节。为了让数据访问层更加简洁、高效且易于维护,许多开发者会选择成熟的 ORM(对象关系映射)框架,SqlSugar 就是其中备受…...
Typeerror: cannot read properties of undefined (reading ‘XXX‘)
最近需要在离线机器上运行软件,所以得把软件用docker打包起来,大部分功能都没问题,出了一个奇怪的事情。同样的代码,在本机上用vscode可以运行起来,但是打包之后在docker里出现了问题。使用的是dialog组件,…...

微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据
微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据 Power Query 具有大量专门帮助您清理和准备数据以供分析的功能。 您将了解如何简化复杂模型、更改数据类型、重命名对象和透视数据。 您还将了解如何分析列,以便知晓哪些列包含有价值的数据,…...
Linux C语言网络编程详细入门教程:如何一步步实现TCP服务端与客户端通信
文章目录 Linux C语言网络编程详细入门教程:如何一步步实现TCP服务端与客户端通信前言一、网络通信基础概念二、服务端与客户端的完整流程图解三、每一步的详细讲解和代码示例1. 创建Socket(服务端和客户端都要)2. 绑定本地地址和端口&#x…...
C语言中提供的第三方库之哈希表实现
一. 简介 前面一篇文章简单学习了C语言中第三方库(uthash库)提供对哈希表的操作,文章如下: C语言中提供的第三方库uthash常用接口-CSDN博客 本文简单学习一下第三方库 uthash库对哈希表的操作。 二. uthash库哈希表操作示例 u…...

c++第七天 继承与派生2
这一篇文章主要内容是 派生类构造函数与析构函数 在派生类中重写基类成员 以及多继承 第一部分:派生类构造函数与析构函数 当创建一个派生类对象时,基类成员是如何初始化的? 1.当派生类对象创建的时候,基类成员的初始化顺序 …...
Java 与 MySQL 性能优化:MySQL 慢 SQL 诊断与分析方法详解
文章目录 一、开启慢查询日志,定位耗时SQL1.1 查看慢查询日志是否开启1.2 临时开启慢查询日志1.3 永久开启慢查询日志1.4 分析慢查询日志 二、使用EXPLAIN分析SQL执行计划2.1 EXPLAIN的基本使用2.2 EXPLAIN分析案例2.3 根据EXPLAIN结果优化SQL 三、使用SHOW PROFILE…...

在Zenodo下载文件 用到googlecolab googledrive
方法:Figshare/Zenodo上的数据/文件下载不下来?尝试利用Google Colab :https://zhuanlan.zhihu.com/p/1898503078782674027 参考: 通过Colab&谷歌云下载Figshare数据,超级实用!!࿰…...