使用RSA算法加密字符串C++
时间: 2024-06-13 07:06:52 浏览: 15
使用RSA算法加密字符串的步骤如下:
1.生成RSA密钥对,包括公钥和私钥。可以使用openssl库中的RSA_generate_key函数生成密钥对。
2.使用公钥对明文进行加密。可以使用openssl库中的RSA_public_encrypt函数进行加密。
3.使用私钥对密文进行解密。可以使用openssl库中的RSA_private_decrypt函数进行解密。
下面是一个使用openssl库实现RSA加密的C++代码示例:
```c++
#include <openssl/rsa.h>
#include <openssl/pem.h>
int main()
{
// 生成RSA密钥对
RSA *keypair = RSA_generate_key(2048, RSA_F4, NULL, NULL);
if (keypair == NULL) {
printf("Failed to generate RSA key pair\n");
return -1;
}
// 明文
const char *plaintext = "Hello, world!";
// 计算加密后的密文长度
int ciphertext_len = RSA_size(keypair);
unsigned char *ciphertext = new unsigned char[ciphertext_len];
// 使用公钥加密明文
int len = RSA_public_encrypt(strlen(plaintext) + 1, (unsigned char *)plaintext, ciphertext, keypair, RSA_PKCS1_PADDING);
if (len == -1) {
printf("Failed to encrypt plaintext\n");
return -1;
}
// 计算解密后的明文长度
int plaintext_len = RSA_size(keypair);
unsigned char *decrypted = new unsigned char[plaintext_len];
// 使用私钥解密密文
len = RSA_private_decrypt(ciphertext_len, ciphertext, decrypted, keypair, RSA_PKCS1_PADDING);
if (len == -1) {
printf("Failed to decrypt ciphertext\n");
return -1;
}
// 输出解密后的明文
printf("Decrypted plaintext: %s\n", decrypted);
// 释放内存
RSA_free(keypair);
delete[] ciphertext;
delete[] decrypted;
return 0;
}
```