公钥密码算法的c++代码
时间: 2024-03-28 13:34:11 浏览: 92
公钥密码算法是一种使用公钥和私钥进行加密和解密的密码算法。在C++中,可以使用OpenSSL库来实现公钥密码算法。下面是一个使用RSA算法的示例代码:
```cpp
#include <iostream>
#include <openssl/rsa.h>
#include <openssl/pem.h>
int main() {
// 生成RSA密钥对
RSA* rsa = RSA_generate_key(2048, RSA_F4, nullptr, nullptr);
// 获取公钥和私钥
BIO* bio_pub = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPublicKey(bio_pub, rsa);
char* pub_key;
long pub_key_len = BIO_get_mem_data(bio_pub, &pub_key);
BIO* bio_pri = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(bio_pri, rsa, nullptr, nullptr, 0, nullptr, nullptr);
char* pri_key;
long pri_key_len = BIO_get_mem_data(bio_pri, &pri_key);
// 加密
std::string plaintext = "Hello, world!";
std::vector<unsigned char> ciphertext(RSA_size(rsa));
int ciphertext_len = RSA_public_encrypt(plaintext.size(), reinterpret_cast<const unsigned char*>(plaintext.c_str()), ciphertext.data(), rsa, RSA_PKCS1_PADDING);
// 解密
std::vector<unsigned char> decryptedtext(RSA_size(rsa));
int decryptedtext_len = RSA_private_decrypt(ciphertext_len, ciphertext.data(), decryptedtext.data(), rsa, RSA_PKCS1_PADDING);
// 输出结果
std::cout << "Plaintext: " << plaintext << std::endl;
std::cout << "Ciphertext: ";
for (int i = 0; i < ciphertext_len; ++i) {
printf("%02X", ciphertext[i]);
}
std::cout << std::endl;
std::cout << "Decryptedtext: " << std::string(decryptedtext.begin(), decryptedtext.begin() + decryptedtext_len) << std::endl;
// 释放资源
RSA_free(rsa);
BIO_free_all(bio_pub);
BIO_free_all(bio_pri);
return 0;
}
```
阅读全文