c++ openssl 使用ECC算法对大文件进行非对称加密和解密示例代码

时间: 2024-01-08 13:02:03 浏览: 32
以下是使用 OpenSSL 的 ECC 算法对大文件进行非对称加密和解密的示例代码: 加密: ```c++ #include <openssl/ec.h> #include <openssl/ecdh.h> #include <openssl/ecdsa.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/err.h> int ecc_encrypt(const char *pubkey_file, const char *input_file, const char *output_file) { EVP_PKEY *pubkey = NULL; FILE *infile = NULL, *outfile = NULL; EC_KEY *ec_key = NULL; int ret = 0; // 读取公钥 pubkey = EVP_PKEY_new(); if (!pubkey) { fprintf(stderr, "Failed to create new EVP_PKEY\n"); goto cleanup; } infile = fopen(pubkey_file, "rb"); if (!infile) { fprintf(stderr, "Failed to open pubkey file: %s\n", pubkey_file); goto cleanup; } if (!PEM_read_PUBKEY(infile, &pubkey, NULL, NULL)) { fprintf(stderr, "Failed to read pubkey from file: %s\n", pubkey_file); ERR_print_errors_fp(stderr); goto cleanup; } // 生成临时密钥对 ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (!ec_key) { fprintf(stderr, "Failed to create new EC_KEY\n"); goto cleanup; } if (!EC_KEY_generate_key(ec_key)) { fprintf(stderr, "Failed to generate EC key\n"); ERR_print_errors_fp(stderr); goto cleanup; } // 构造密钥交换对象 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pubkey, NULL); if (!pctx) { fprintf(stderr, "Failed to create new EVP_PKEY_CTX\n"); goto cleanup; } if (EVP_PKEY_derive_init(pctx) <= 0) { fprintf(stderr, "Failed to initialize EVP_PKEY_CTX\n"); ERR_print_errors_fp(stderr); goto cleanup; } if (EVP_PKEY_derive_set_peer(pctx, pubkey) <= 0) { fprintf(stderr, "Failed to set peer pubkey for EVP_PKEY_CTX\n"); ERR_print_errors_fp(stderr); goto cleanup; } size_t len; if (EVP_PKEY_derive(pctx, NULL, &len) <= 0) { fprintf(stderr, "Failed to get derived key length\n"); ERR_print_errors_fp(stderr); goto cleanup; } unsigned char *key = (unsigned char *) malloc(len); if (!key) { fprintf(stderr, "Failed to allocate memory for derived key\n"); goto cleanup; } if (EVP_PKEY_derive(pctx, key, &len) <= 0) { fprintf(stderr, "Failed to derive key\n"); ERR_print_errors_fp(stderr); goto cleanup; } EVP_PKEY_CTX_free(pctx); pctx = NULL; // 生成随机 IV unsigned char iv[EVP_MAX_IV_LENGTH]; if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0) { fprintf(stderr, "Failed to generate IV\n"); ERR_print_errors_fp(stderr); goto cleanup; } // 加密 int block_size = EVP_CIPHER_block_size(EVP_aes_256_cbc()); unsigned char *in_buf = (unsigned char *) malloc(block_size); unsigned char *out_buf = (unsigned char *) malloc(block_size + EVP_MAX_IV_LENGTH); if (!in_buf || !out_buf) { fprintf(stderr, "Failed to allocate memory for read/write buffer\n"); goto cleanup; } infile = fopen(input_file, "rb"); if (!infile) { fprintf(stderr, "Failed to open input file: %s\n", input_file); goto cleanup; } outfile = fopen(output_file, "wb"); if (!outfile) { fprintf(stderr, "Failed to open output file: %s\n", output_file); goto cleanup; } // 写入 IV 到输出文件 fwrite(iv, 1, EVP_MAX_IV_LENGTH, outfile); EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if (!ctx) { fprintf(stderr, "Failed to create new EVP_CIPHER_CTX\n"); goto cleanup; } if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv) <= 0) { fprintf(stderr, "Failed to initialize encryption context\n"); ERR_print_errors_fp(stderr); goto cleanup; } int bytes_read, bytes_written; while ((bytes_read = fread(in_buf, 1, block_size, infile)) > 0) { if (EVP_EncryptUpdate(ctx, out_buf, &bytes_written, in_buf, bytes_read) <= 0) { fprintf(stderr, "Failed to encrypt data\n"); ERR_print_errors_fp(stderr); goto cleanup; } fwrite(out_buf, 1, bytes_written, outfile); } if (EVP_EncryptFinal_ex(ctx, out_buf, &bytes_written) <= 0) { fprintf(stderr, "Failed to finalize encryption\n"); ERR_print_errors_fp(stderr); goto cleanup; } fwrite(out_buf, 1, bytes_written, outfile); ret = 1; cleanup: if (pubkey) { EVP_PKEY_free(pubkey); } if (infile) { fclose(infile); } if (outfile) { fclose(outfile); } if (ec_key) { EC_KEY_free(ec_key); } if (pctx) { EVP_PKEY_CTX_free(pctx); } if (key) { free(key); } if (in_buf) { free(in_buf); } if (out_buf) { free(out_buf); } if (ctx) { EVP_CIPHER_CTX_free(ctx); } return ret; } ``` 解密: ```c++ #include <openssl/ec.h> #include <openssl/ecdh.h> #include <openssl/ecdsa.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/err.h> int ecc_decrypt(const char *privkey_file, const char *input_file, const char *output_file) { EVP_PKEY *privkey = NULL; FILE *infile = NULL, *outfile = NULL; EC_KEY *ec_key = NULL; int ret = 0; // 读取私钥 privkey = EVP_PKEY_new(); if (!privkey) { fprintf(stderr, "Failed to create new EVP_PKEY\n"); goto cleanup; } infile = fopen(privkey_file, "rb"); if (!infile) { fprintf(stderr, "Failed to open privkey file: %s\n", privkey_file); goto cleanup; } if (!PEM_read_PrivateKey(infile, &privkey, NULL, NULL)) { fprintf(stderr, "Failed to read privkey from file: %s\n", privkey_file); ERR_print_errors_fp(stderr); goto cleanup; } // 构造密钥交换对象 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(privkey, NULL); if (!pctx) { fprintf(stderr, "Failed to create new EVP_PKEY_CTX\n"); goto cleanup; } if (EVP_PKEY_derive_init(pctx) <= 0) { fprintf(stderr, "Failed to initialize EVP_PKEY_CTX\n"); ERR_print_errors_fp(stderr); goto cleanup; } // 读取 IV unsigned char iv[EVP_MAX_IV_LENGTH]; size_t iv_len = fread(iv, 1, EVP_MAX_IV_LENGTH, infile); if (EVP_PKEY_derive_set_peer(pctx, EVP_PKEY_get1_EC_KEY(privkey)) <= 0) { fprintf(stderr, "Failed to set peer pubkey for EVP_PKEY_CTX\n"); ERR_print_errors_fp(stderr); goto cleanup; } size_t len; if (EVP_PKEY_derive(pctx, NULL, &len) <= 0) { fprintf(stderr, "Failed to get derived key length\n"); ERR_print_errors_fp(stderr); goto cleanup; } unsigned char *key = (unsigned char *) malloc(len); if (!key) { fprintf(stderr, "Failed to allocate memory for derived key\n"); goto cleanup; } if (EVP_PKEY_derive(pctx, key, &len) <= 0) { fprintf(stderr, "Failed to derive key\n"); ERR_print_errors_fp(stderr); goto cleanup; } EVP_PKEY_CTX_free(pctx); pctx = NULL; // 解密 int block_size = EVP_CIPHER_block_size(EVP_aes_256_cbc()); unsigned char *in_buf = (unsigned char *) malloc(block_size + EVP_MAX_IV_LENGTH); unsigned char *out_buf = (unsigned char *) malloc(block_size); if (!in_buf || !out_buf) { fprintf(stderr, "Failed to allocate memory for read/write buffer\n"); goto cleanup; } infile = fopen(input_file, "rb"); if (!infile) { fprintf(stderr, "Failed to open input file: %s\n", input_file); goto cleanup; } outfile = fopen(output_file, "wb"); if (!outfile) { fprintf(stderr, "Failed to open output file: %s\n", output_file); goto cleanup; } EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if (!ctx) { fprintf(stderr, "Failed to create new EVP_CIPHER_CTX\n"); goto cleanup; } if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv) <= 0) { fprintf(stderr, "Failed to initialize decryption context\n"); ERR_print_errors_fp(stderr); goto cleanup; } int bytes_read, bytes_written; while ((bytes_read = fread(in_buf, 1, block_size + iv_len, infile)) > 0) { if (EVP_DecryptUpdate(ctx, out_buf, &bytes_written, in_buf + iv_len, bytes_read - iv_len) <= 0) { fprintf(stderr, "Failed to decrypt data\n"); ERR_print_errors_fp(stderr); goto cleanup; } fwrite(out_buf, 1, bytes_written, outfile); memmove(iv, in_buf, iv_len); } if (EVP_DecryptFinal_ex(ctx, out_buf, &bytes_written) <= 0) { fprintf(stderr, "Failed to finalize decryption\n"); ERR_print_errors_fp(stderr); goto cleanup; } fwrite(out_buf, 1, bytes_written, outfile); ret = 1; cleanup: if (privkey) { EVP_PKEY_free(privkey); } if (infile) { fclose(infile); } if (outfile) { fclose(outfile); } if (ec_key) { EC_KEY_free(ec_key); } if (pctx) { EVP_PKEY_CTX_free(pctx); } if (key) { free(key); } if (in_buf) { free(in_buf); } if (out_buf) { free(out_buf); } if (ctx) { EVP_CIPHER_CTX_free(ctx); } return ret; } ``` 注意,在上述代码中,我们使用了“密钥交换”的方式来实现加密和解密。具体来说,我们先读取目标方(解密方)的公钥,然后生成一个临时的 ECC 密钥对,使用目标方的公钥和临时密钥对进行密钥交换,得到一个共享密钥,用这个共享密钥对大文件进行加密。解密时,我们读取自己的私钥,并使用共享密钥对大文件进行解密。这样做的好处是,即使黑客截获了加密后的文件和临时密钥对,也无法得到共享密钥,因为共享密钥是在密钥交换的过程中生成的,并不会被传输。

相关推荐

最新推荐

recommend-type

python加密解密库cryptography使用openSSL生成的密匙加密解密

主要介绍了python加密解密库cryptography使用openSSL生成的密匙加密解密,需要的朋友可以参考下
recommend-type

C语言使用openSSL库AES模块实现加密功能详解

主要介绍了C语言使用openSSL库AES模块实现加密功能,详细分析了C语言加密的相关概念、原理及AES模块加密具体实现技巧,需要的朋友可以参考下
recommend-type

Windows安装配置C/C++(VS2017)OpenSSL开发环境配置教程

主要为大家详细介绍了Windows安装配置C/C++,OpenSSL开发环境配置教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

C语言使用openSSL库DES模块实现加密功能详解

主要介绍了C语言使用openSSL库DES模块实现加密功能,简单讲解了DES加密的相关概念,并结合实例形式分析了DES加密的具体实现技巧,需要的朋友可以参考下
recommend-type

基于Android 7.0与Android Studio的安卓学习.zip

Android是一种基于Linux内核(不包含GNU组件)的自由及开放源代码的移动操作系统,主要应用于移动设备,如智能手机和平板电脑。该系统最初由安迪·鲁宾开发,后被Google公司收购并注资,随后与多家硬件制造商、软件开发商及电信营运商共同研发改良。 Android操作系统的特点包括: 开放源代码:Android系统采用开放源代码模式,允许开发者自由访问、修改和定制操作系统,这促进了技术的创新和发展,使得Android系统具有高度的灵活性和可定制性。 多任务处理:Android允许用户同时运行多个应用程序,并且可以轻松地在不同应用程序之间切换,提高了效率和便利性。 丰富的应用生态系统:Android系统拥有庞大的应用程序生态系统,用户可以从Google Play商店或其他第三方应用市场下载和安装各种各样的应用程序,满足各种需求。 可定制性:Android操作系统可以根据用户的个人喜好进行定制,用户可以更改主题、小部件和图标等,以使其界面更符合个人风格和偏好。 多种设备支持:Android操作系统可以运行在多种不同类型的设备上,包括手机、平板电脑、智能电视、汽车导航系统等。 此外,Android系统还有一些常见的问题,如应用崩溃、电池耗电过快、Wi-Fi连接问题、存储空间不足、更新问题等。针对这些问题,用户可以尝试一些基本的解决方法,如清除应用缓存和数据、降低屏幕亮度、关闭没有使用的连接和传感器、限制后台运行的应用、删除不需要的文件和应用等。 随着Android系统的不断发展,其功能和性能也在不断提升。例如,最新的Android版本引入了更多的安全性和隐私保护功能,以及更流畅的用户界面和更强大的性能。此外,Android系统也在不断探索新的应用场景,如智能家居、虚拟现实、人工智能等领域。 总之,Android系统是一种功能强大、灵活可定制、拥有丰富应用生态系统的移动操作系统,在全球范围内拥有广泛的用户基础。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

spring添加xml配置文件

1. 创建一个新的Spring配置文件,例如"applicationContext.xml"。 2. 在文件头部添加XML命名空间和schema定义,如下所示: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。