gpt4 book ai didi

c++ - OpenSSL:RSA 加密/解密、 key 生成和 key 持久性

转载 作者:可可西里 更新时间:2023-11-01 17:52:13 26 4
gpt4 key购买 nike

我正在尝试构建一个需要以下内容的 p2p 应用程序,在 OpenSSL 中使用 RSA:

-Encryption
-Decryption
-Generating Keys (done)
-Saving and loading keys (done)
-Saving the PUBLIC key as bytes so it can be sent over the sockets
-Loading keys from the above format

我已选择使用 EVP 功能,无论这意味着什么。然而,我很难找到我需要使用哪些功能来做这些事情,以及以什么顺序。 OpenSSL 的官方文档似乎不存在。

有谁知道我需要按什么顺序使用哪些功能以及它们的原型(prototype)?随处可见的任何示例代码也很好。

提前致谢

twitchliquid64。

PS:这是我目前所拥有的

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/engine.h>
#include <openssl/rand.h>

RSA* Generate_KeyPair(void)
{
char rand_buff[16];
EVP_PKEY *pkey = NULL;
RSA* r;
char* pass = "passgdfgf";//for now

int bits = 512; // 512, 1024, 2048, 4096
unsigned long exp = RSA_F4; // RSA_3
OpenSSL_add_all_algorithms();

RAND_seed(rand_buff, 16); //On linux: RAND_load_file("/dev/urandom", 1024);
r = RSA_generate_key(bits,exp,NULL,NULL);

if (RSA_check_key(r)!=1);;; //Check key - error out

//Create EVP to save to file.
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, r);

//Save private key
FILE* fp = fopen("private.key", "w");
PEM_write_PrivateKey(fp,pkey,EVP_aes_256_cbc(),NULL,0,NULL,pass)
fclose(fp);

//Save public key
fp = fopen("public.key", "w");
PEM_write_PUBKEY(fp, pkey);
fclose(fp);

return r;
}

EVP_PKEY* ReadPrivKey_FromFile(char* filename, char* pass)
{
FILE* fp = fopen(filename, "r");
EVP_PKEY* key = NULL;
PEM_read_PrivateKey(fp, &key, NULL, pass);
fclose(fp);

return key;
}

EVP_PKEY* ReadPubKey_FromFile(char* filename)
{
FILE* fp = fopen(filename, "r");
EVP_PKEY* key = NULL;
PEM_read_PUBKEY(fp, &key, NULL, NULL);
fclose(fp);

return key;
}

最佳答案

正如在对我的问题的评论中所说:

您会发现 OpenSSL 附带的示例代码比文档更有用。例如,使用 RSA 加密的文档显示在 apps/rsa.c 中。这可能有助于计算出 OpenSSL 命令行以执行您想使用命令行工具执行的每个功能,然后找出代码实际执行的操作(通过检查),这样您就可以让您的代码执行相同的操作。– 大卫·施瓦茨

这个示例代码正是我所需要的,我建议任何有类似问题的人查阅 rsa 代码和头文件,以及它们在文档中的小使用示例。

关于c++ - OpenSSL:RSA 加密/解密、 key 生成和 key 持久性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10779027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com