我正在开发一个简单的类来加密和解密xcode中的字符串。这是代码:
.h文件
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/err.h>
class rsa
{
char * public_key;
char * private_key;
int padding = RSA_PKCS1_PADDING;
public:
//Constructors
rsa();
rsa(char *, char *);
// Methods
unsigned char * public_encrypt(char *);
private:
// Private Methods
RSA * generate_rsa(bool public_key);
};
.cpp文件
#include "rsa.h"
rsa :: rsa(char * public_key, char * private_key)
{
this->public_key = public_key;
this->private_key = private_key;
}
unsigned char * rsa :: public_encrypt(char * from)
{
unsigned char * result;
int encrypted_len;
RSA *rsa = this->generate_rsa(true);
result = (unsigned char *) malloc(RSA_size(rsa));
RSA_public_encrypt(strlen(from), from, result, rsa, RSA_PKCS1_OAEP_PADDING);
return result;
}
RSA * rsa :: generate_rsa(bool public_key)
{
RSA *rsa = NULL;
if(public_key)
{
BIO *keybio = BIO_new_mem_buf(this->public_key, -1);
rsa = PEM_read_bio_RSA_PUBKEY(keybio, &rsa,NULL, NULL);
}
else
{
BIO *keybio = BIO_new_mem_buf(this->private_key, -1);
rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa,NULL, NULL);
}
return rsa;
}
我想做的就是使用我的公钥加密字符串。但xcode告诉我几乎所有openssl函数如RSA_public_encrypt和RSA_size都是从OSX 10.7中弃用的。
这是 main.cpp :
int main()
{
char * privateKey = "-----BEGIN RSA PRIVATE KEY-----\n"\
"MIGrAgEAAiEAy6uf9MPG6ohi/3pVEl3o/9NMZfKIMbhQbT09u6IQsd0CAwEAAQIh\n"\
"AKT8TWI4qc1ZWGC+V2W+fzwxjidtIwW3xZasDUlrlWodAhEA/bCcdSA0H/AmW/U0\n"\
"SXuhKwIRAM2GaSwJPLoenfzttkP+JRcCEQDdiq4XWtgqS/4zsB7JTT2hAhBAEM8G\n"\
"ABci+VpMNpljVnyfAhAlce8wS5CQF432ue8VUoMr\n"\
"-----END RSA PRIVATE KEY-----";
char * publicKey ="-----BEGIN PUBLIC KEY-----\n"\
"MDwwDQYJKoZIhvcNAQEBBQADKwAwKAIhAMurn/TDxuqIYv96VRJd6P/TTGXyiDG4\n"\
"UG09PbuiELHdAgMBAAE=\n"\
"-----END PUBLIC KEY-----";
char * test = "testestest!";
rsa my_rsa(publicKey, privateKey);
cout<<my_rsa.public_encrypt(test)<<endl;
}
此代码在xcode中无法使用。我期待我的&#34; testestest&#34;的十六进制输出。字符串,但结果缓冲区为空。没有错误,只有很多关于弃用的警告。哪里错了?我该怎么办?我搜索过网站和openssl网站,但我无法理解如何做到这一点。 谢谢你的每一个建议。