正如 comments 中所证明的那样,RSA是您可以接受的选项.
在使用OpenSSL实施RSA时,需要执行以下步骤进行加密:
下面的RSA和OpenSSL加密实现在我的机器上成功运行,并显示了如何调用这些函数(为简单起见,没有异常处理):
#include <openssl/pem.h>
#include <string>
...
bool EncryptString(const std::string& InStr /*plaintext*/, const std::string& InPublicKey /*path to public key pem file*/, std::string& OutString /*ciphertext*/) {
// Load key
FILE* f = fopen(InPublicKey.c_str(), "r");
EVP_PKEY* pkey = PEM_read_PUBKEY(f, NULL, NULL, NULL);
fclose(f);
// Create/initialize context
EVP_PKEY_CTX* ctx;
ctx = EVP_PKEY_CTX_new(pkey, NULL);
EVP_PKEY_encrypt_init(ctx);
// Specify padding: default is PKCS#1 v1.5
// EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING); // for OAEP with SHA1 for both digests
// 加密法
size_t ciphertextLen;
EVP_PKEY_encrypt(ctx, NULL, &ciphertextLen, (const unsigned char*)InStr.c_str(), InStr.size());
unsigned char* ciphertext = (unsigned char*)OPENSSL_malloc(ciphertextLen);
EVP_PKEY_encrypt(ctx, ciphertext, &ciphertextLen, (const unsigned char*)InStr.c_str(), InStr.size());
OutString.assign((char*)ciphertext, ciphertextLen);
// Release memory
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(ctx);
OPENSSL_free(ciphertext);
return true; // add exception/error handling
}
对于密文,必须认为它是不代表真实文本的字节序列(例如,它可能包含0x00值).如果要将密文表示为真实文本,则必须执行额外的二进制到文本编码,例如Base64编码.
该代码需要X.509/SPKI格式的PEM编码公钥.如果公钥具有PKCS#1格式,则可以使用PEM_read_RSAPublicKey()
和EVP_PKEY_set1_RSA()
导入.