在vs2019中rsa加解密算法代码c++
时间: 2023-09-28 07:07:56 浏览: 54
以下是一个简单的RSA加解密算法的C++代码示例,使用了VS2019的C++编译器。代码中使用了OpenSSL库实现RSA算法,所以需要安装OpenSSL库。
```cpp
#include <iostream>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <cstring>
using namespace std;
// 生成RSA密钥对(公钥和私钥)
bool generateRSAKeyPair(RSA*& publicKey, RSA*& privateKey) {
// 生成RSA密钥对
int bits = 2048; // 密钥长度
unsigned long e = RSA_F4; // 加密指数
BIGNUM* bn = BN_new();
BN_set_word(bn, e);
if (!RSA_generate_key_ex(publicKey, bits, bn, nullptr) || !RSA_generate_key_ex(privateKey, bits, bn, nullptr)) {
return false;
}
BN_free(bn);
return true;
}
// RSA加密
int rsaEncrypt(const RSA* publicKey, const unsigned char* plainText, const size_t plainTextLength, unsigned char*& cipherText) {
int ret = 0;
int rsaLength = RSA_size(publicKey); // RSA密钥长度
cipherText = new unsigned char[rsaLength];
memset(cipherText, 0, rsaLength);
ret = RSA_public_encrypt(plainTextLength, plainText, cipherText, const_cast<RSA*>(publicKey), RSA_PKCS1_PADDING);
if (ret == -1) {
delete[] cipherText;
cipherText = nullptr;
}
return ret;
}
// RSA解密
int rsaDecrypt(const RSA* privateKey, const unsigned char* cipherText, const size_t cipherTextLength, unsigned char*& plainText) {
int ret = 0;
int rsaLength = RSA_size(privateKey); // RSA密钥长度
plainText = new unsigned char[rsaLength];
memset(plainText, 0, rsaLength);
ret = RSA_private_decrypt(cipherTextLength, cipherText, plainText, const_cast<RSA*>(privateKey), RSA_PKCS1_PADDING);
if (ret == -1) {
delete[] plainText;
plainText = nullptr;
}
return ret;
}
int main() {
OpenSSL_add_all_algorithms(); // 初始化OpenSSL
// 生成RSA密钥对
RSA* publicKey = RSA_new();
RSA* privateKey = RSA_new();
if (!generateRSAKeyPair(publicKey, privateKey)) {
cout << "Generate RSA key pair failed." << endl;
return -1;
}
// 明文
const string plainText = "Hello, world!";
const size_t plainTextLength = plainText.length();
// RSA加密
unsigned char* cipherText = nullptr;
int cipherTextLength = rsaEncrypt(publicKey, reinterpret_cast<const unsigned char*>(plainText.c_str()), plainTextLength, cipherText);
if (cipherText == nullptr || cipherTextLength == -1) {
cout << "RSA encryption failed." << endl;
RSA_free(publicKey);
RSA_free(privateKey);
return -1;
}
// 输出密文
cout << "Cipher text: ";
for (int i = 0; i < cipherTextLength; i++) {
printf("%02x", cipherText[i]);
}
cout << endl;
// RSA解密
unsigned char* decryptedPlainText = nullptr;
int decryptedPlainTextLength = rsaDecrypt(privateKey, cipherText, cipherTextLength, decryptedPlainText);
if (decryptedPlainText == nullptr || decryptedPlainTextLength == -1) {
cout << "RSA decryption failed." << endl;
RSA_free(publicKey);
RSA_free(privateKey);
delete[] cipherText;
return -1;
}
// 输出解密后的明文
cout << "Decrypted plain text: " << decryptedPlainText << endl;
// 释放内存
delete[] cipherText;
delete[] decryptedPlainText;
RSA_free(publicKey);
RSA_free(privateKey);
return 0;
}
```
注意:此代码示例没有进行异常处理和错误处理,实际使用中需要根据实际情况进行处理。