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整体设计当中,它是有一些特定的用处和一些…...
Java SSRF漏洞深度解析:从URLConnection安全风险到多层防御实战
1. 项目概述:从两个看似简单的API说起在Java开发中,URLConnection和openStream()这两个方法几乎是每个开发者入门网络编程时最早接触的API。它们简单、直观,几行代码就能实现从网络获取数据的功能。然而,正是这种“简单易用”的特…...
Medium作者收益预测模型:轻量可解释的写作价值评估系统
1. 项目概述:这不是一个“预测收入”的模型,而是一套写作者价值评估系统你点开这个标题,第一反应可能是:“哦,又一个用机器学习算稿费的工具?”——但实际远不止如此。Medium writer earnings(M…...
专栏导读:为什么需要从 MM 理解 HMM
一个真实的困境 假设你是一个 GPU 计算框架的开发者。用户写了这样一段代码: float *data malloc(1GB); // ... 填充数据 ... gpu_kernel<<<grid, block>>>(data); // 希望 GPU 直接访问 data在传统编程模型下,这不可能工作——GPU …...
保姆级教程:用ArcGIS Pro搞定全国30米DEM数据下载与无缝拼接(附避坑指南)
全国30米DEM数据高效处理:ArcGIS Pro全流程实战指南 对于GIS从业者和研究者来说,获取并处理全国范围的数字高程模型(DEM)数据是一项基础但关键的工作。传统方法往往效率低下且容易出错,而ArcGIS Pro凭借其现代化架构和强大工具链,…...
STM32矩阵按键详解——4×4行列扫描与非阻塞消抖(硬件总结六)
前言 独立按键虽然简单,但当产品需要十几个按键时,每个按键独占一个GPIO的接法就变得很不经济。矩阵按键通过“行列”的交叉结构,仅用NM个GPIO即可驱动NM个按键。以最常见的44矩阵为例,16个按键仅需8个GPIO,引脚利用率…...
终极QR码修复指南:如何用QrazyBox免费恢复损坏的二维码
终极QR码修复指南:如何用QrazyBox免费恢复损坏的二维码 【免费下载链接】qrazybox QR Code Analysis and Recovery Toolkit 项目地址: https://gitcode.com/gh_mirrors/qr/qrazybox 你是否曾遇到过重要的二维码因为打印模糊、水渍污染或物理磨损而无法扫描&a…...
OBS智能背景移除插件:零绿幕实现专业直播效果的完整指南
OBS智能背景移除插件:零绿幕实现专业直播效果的完整指南 【免费下载链接】obs-backgroundremoval An OBS plugin for removing background in portrait images (video), making it easy to replace the background when recording or streaming. 项目地址: https:…...
3分钟完成Excel批量查询:智能多文件搜索工具完整指南
3分钟完成Excel批量查询:智能多文件搜索工具完整指南 【免费下载链接】QueryExcel 多Excel文件内容查询工具。 项目地址: https://gitcode.com/gh_mirrors/qu/QueryExcel 还在为处理海量Excel文件而烦恼吗?面对成百上千个表格文件,传统…...
免费开源AMD Ryzen调试工具SMUDebugTool:释放处理器性能的终极指南
免费开源AMD Ryzen调试工具SMUDebugTool:释放处理器性能的终极指南 【免费下载链接】SMUDebugTool A dedicated tool to help write/read various parameters of Ryzen-based systems, such as manual overclock, SMU, PCI, CPUID, MSR and Power Table. 项目地址…...
2026年AI面试准确率TOP榜:92%一致性背后,谁在定义行业新标准?
当年ChatGPT的横空出世,让全世界第一次见识到通用大模型的对话能力;DeepSeek 的爆发,则将AI的火种真正播撒到中国各行各业的毛细血管中,而在人力资源行业作为数字化转型的前沿阵地,首当其冲迎来了AI的全面渗透 &#x…...
