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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/621242.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

经典目标检测YOLO系列(二)YOLOv2算法详解

经典目标检测YOLO系列(二)YOLOv2算法详解 YOLO-V1以完全端到端的模式实现达到实时水平的目标检测。但是&#xff0c;YOLO-V1为追求速度而牺牲了部分检测精度&#xff0c;在检测速度广受赞誉的同时&#xff0c;其检测精度也饱受诟病。正是由于这个原因&#xff0c;YOLO团队在20…

TIDB: 元数据查询语句

一、获取表描述 select table_name,table_comment from information_schema.TABLES where table_schema %s and table_name in (%s)二、获取视图DDL SELECT * FROM information_schema.views WHERE TABLE_NAME %s and TABLE_SCHEMA %s三、判断表是否存在sql select table…

clickhouse join查询算法

算法对比&#xff1a; 使用方法&#xff1a; SELECT town,max(price) AS max_price,any(population) AS population FROM uk_xxx_paid JOIN uk_xxx_table ON lower(uk_price_paid.town) lower(uk_populations_table.city) GROUP BY town ORDER BY max_price DESC SETTINGS jo…

PLC-IoT 网关开发札记(3):Xamarin Forms 首页跳转的正确姿势

1. 需求 使用 Xamarin.Forms 默认的模板生成卡片式 App 项目后&#xff0c;App 打开的是第一个卡片页。实用中&#xff0c;往往需要 App 启动后呈现一个 Splash&#xff0c;在 Splash 页面的后台完成系统初始化的一些任务&#xff0c;然后自动跳转或者等待用户点击 “立即体验…

代码随想录 Leetcode349. 两个数组的交集

题目&#xff1a; 代码(首刷看解析 2024年1月14日&#xff09;&#xff1a; class Solution { public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {unordered_set<int> a;unordered_set<int> res;for(int i 0…

Centos7 安装与卸载mysql

卸载 ps ajx | grep mysql &#xff1a; 查看当前服务器是否有mysql 没有的话就不需要卸载咯。 centos7 通过yum下载安装包通常是以.rpm为后缀&#xff0c;rpm -qa 可以查看当前服务器上所有的安装包&#xff1a; rpm -qa | grep mysql | xargs yum -y remove :将查询到的mysql…

AI辅助编程:同义千问挑战力扣

大家好我是在看&#xff0c;记录普通人学习探索AI之路。 今天我们来聊一聊如何使用AI进行辅助编程。 ChatGPT对于各行各业都带来了工作效率的提升&#xff0c;尤其是程序员这一行。因为ChatGPT可以帮助程序员来生成各种各样的程序代码。 我们先来看一个简单的例子&#xff0c…

多行SQL转成单行SQL

如下图所示 将以上多行SQL转成单行SQL 正则表达式如下 (?s)$[^a-zA-Z()0-9]*结果如下 灵活使用,也未必只能使用Sublime Text

js null和undefined的区别

null和undefined在JavaScript中都表示“无”的概念&#xff0c;但它们在使用和含义上有一些重要的区别。 含义&#xff1a; null 是一个表示“无”的对象&#xff0c;当转换为数值时结果为0。 undefined 是一个表示“缺少值”的原始值&#xff0c;当转换为数值时结果为NaN。…

用java写个redis工具类

下面是一个简单的Redis工具类的示例&#xff0c;使用Java语言编写&#xff1a; import redis.clients.jedis.Jedis;public class RedisUtils {private static Jedis jedis;public static void connect(String host, int port) {jedis new Jedis(host, port);}public static v…

python爬虫01-爬虫介绍

目录 1、爬虫是什么 2、爬虫有什么用 3、爬虫的步骤 4、网页的渲染方式 1、爬虫是什么 爬虫就是写一段代码运行去模仿人访问网站。可以代替人们自动的在互联网进行数据采集和整理。 2、爬虫有什么用 数据采集&#xff1a;爬虫可以自动访问网页并抓取其中的数据&#xff0…

基于卡尔曼滤波的视频跟踪,基于卡尔曼滤波的运动小球跟踪

目录 完整代码和数据下载链接&#xff1a;基于卡尔曼滤波的视频跟踪&#xff0c;基于卡尔曼滤波的运动小球跟踪&#xff08;代码完整&#xff0c;数据齐全&#xff09;资源-CSDN文库 https://download.csdn.net/download/abc991835105/88738577 卡尔曼滤波原理 RBF的定义 RBF理…

ajax+axios——统一设置请求头参数——添加请求头入参——基础积累

最近在写后台管理系统&#xff08;我怎么一直都只写管理系统啊啊啊啊啊啊啊&#xff09;&#xff0c;遇到一个需求&#xff0c;就是要在原有系统的基础上&#xff0c;添加一个仓库的切换&#xff0c;并且需要把选中仓库对应的id以请求头参数的形式传递到每一个接口当中。。。 …

4.【CPP】入门(初始化列表||explicit||static||友元||静态成员变量/函数)

一.初始化列表 1.引入 我们知道在c11中才能在成员对象声明时初始化&#xff0c;像下面这样。 class Date { public: Date(int year, int month, int day): _year(year), _month(month), _day(day) {} private: int _year2000; int _month12; int _day20; };注意&#xff1a;…

Redis:原理速成+项目实战——Redis实战9(秒杀优化)

&#x1f468;‍&#x1f393;作者简介&#xff1a;一位大四、研0学生&#xff0c;正在努力准备大四暑假的实习 &#x1f30c;上期文章&#xff1a;Redis&#xff1a;原理速成项目实战——Redis实战8&#xff08;基于Redis的分布式锁及优化&#xff09; &#x1f4da;订阅专栏&…

浅谈一谈pytorch中模型的几种保存方式、以及如何从中止的地方继续开始训练;

一、本文总共介绍3中pytorch模型的保存方式&#xff1a;1.保存整个模型&#xff1b;2.只保存模型参数&#xff1b;3.保存模型参数、优化器、学习率、epoch和其它的所有命令行相关参数以方便从上次中止训练的地方重新启动训练过程。 1.保存整个模型。这种保存方式最简单&#x…

xtu oj 1354 Digit String

题目描述 小明获得了一些密码的片段&#xff0c;包含0∼9,A∼F 这些字符&#xff0c;他猜这些是某个进制下的一个整数的数码串。 小明想知道从2到16进制中&#xff0c;哪些进制下&#xff0c;这个数码串的对应的十进制整数值&#xff0c;等于n? 输入 存在不超过1000个样例&…

C#,史密斯数(Smith Number)的计算方法与源代码

一、关于史密斯数的传说 1、关于理海大学Lehigh University 理海大学&#xff08;Lehigh University&#xff09;&#xff0c;位于宾夕法尼亚州&#xff08;Pennsylvania&#xff09;伯利恒&#xff08;Bethlehem&#xff09;&#xff0c;由富有爱国情怀与民族精神的实业家艾萨…

Java SE入门及基础(12)

do-while 循环 1. 语法 do { //循环操作 } while ( 循环条件 ); 2. 执行流程图 3. 案例 从控制台录入学生的成绩并计算总成绩&#xff0c;输入0 时退出 4. 代码实现 public static void main ( String [] args ) { Scanner sc new Scanner ( System . in )…