RSA加密解密实现C++
时间: 2025-01-10 18:19:39 浏览: 76
### C++ 实现 RSA 加密解密
#### 使用 OpenSSL 库实现 RSA 加密解密功能
为了在 C++ 中实现 RSA 的加密和解密操作,可以借助于 OpenSSL 这一强大的库。下面提供了一个完整的示例程序来展示如何利用公钥进行加密以及私钥来进行相应的解密过程。
```cpp
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/bio.h>
#include <iostream>
// 定义全局变量用于存储文件路径
const char* g_pPubFile = "public_key.pem"; // 公钥文件位置
const char* g_pPriFile = "private_key.pem"; // 私钥文件位置
/// @brief 对输入的数据执行RSA加密处理
/// @param[in] in 输入明文字符串指针
/// @param[in] inLen 明文字节数量
/// @param[out] out 输出密文缓冲区地址
/// @param[out] outLen 返回实际写入的字节长度
/// @return 成功返回0;失败则为负数
int Encrypt(const unsigned char *in, size_t inLen, unsigned char **out, size_t &outLen) {
BIO *bio;
RSA *pubkey;
bio = BIO_new_file(g_pPubFile, "rb");
pubkey = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
BIO_free_all(bio);
if (!pubkey || !in || !out)
return -1;
int rsa_len = RSA_size(pubkey);
*out = new unsigned char[rsa_len];
outLen = RSA_public_encrypt(inLen > (size_t)(rsa_len - 11)?(rsa_len - 11):inLen,
in, *out, pubkey, RSA_PKCS1_PADDING);
RSA_free(pubkey);
return outLen >= 0 ? 0 : -1;
}
/// @brief 执行RSA解密操作
/// @param[in] in 密文数据指针
/// @param[in] inLen 密文字节数量
/// @param[out] out 存储解密后的结果空间首址
/// @param[out] outLen 记录最终得到的有效字符数量
/// @return 正常完成时给出非零值表示成功;反之亦然。
int Decrypt(const unsigned char *in, size_t inLen, unsigned char **out, size_t &outLen){
BIO *bio;
RSA *prikey;
bio=BIO_new_file(g_pPriFile,"rb");
prikey=PEM_read_bio_RSAPrivateKey(bio,NULL,NULL,NULL);
BIO_free_all(bio);
if(!prikey||!in||!out)
return -1;
int rsa_len=RSA_size(prikey);
*out=new unsigned char[rsa_len];
outLen=RSA_private_decrypt((int)inLen,in,*out,prikey,RSA_PKCS1_PADDING);
RSA_free(prikey);
return outLen>=0?0:-1;
}
```
上述代码片段展示了两个主要函数 `Encrypt` 和 `Decrypt` 来分别负责加密与解密工作[^2]。需要注意的是,在调用这些接口之前应当先准备好对应的公钥(`g_pPubFile`)和私钥(`g_pPriFile`)文件,并确保它们能够被正确加载到内存中以便后续使用。
对于每次加密的最大数据长度(block_len),这取决于所使用的RSA秘钥大小(RSA_size())减去填充所需的额外开销。通常情况下采用PKCS#1 v1.5标准下的填充方式会占用大约11个字节的空间,因此有效载荷不得超过剩余部分[^1]。
阅读全文
相关推荐















