RSA
1.密钥生成
void generateKey() {
RSA* rsa = RSA_generate_key(1024, RSA_F4, NULL, NULL);
BIO *bp = BIO_new(BIO_s_file());
BIO_write_filename(bp, "public.pem");
PEM_write_bio_RSAPublicKey(bp, rsa);
BIO_free_all(bp);
bp = BIO_new_file("private.pem", "w+");
PEM_write_bio_RSAPrivateKey(bp, rsa, NULL, NULL, 4, NULL, NULL);
BIO_free_all(bp);
RSA_free(rsa);
}
2.公钥加密
string bio_read_publicKey(string data) {
OpenSSL_add_all_algorithms();
BIO* bp = BIO_new(BIO_s_file());
BIO_read_filename(bp, "public.pem");
RSA* rsaK = PEM_read_bio_RSAPublicKey(bp, NULL, NULL, NULL);
if (NULL == rsaK) {
perror("read key file fail!");
}
else {
printf("read success!");
int nLen = RSA_size(rsaK);
printf("len:%d\n", nLen);
}
int nLen = RSA_size(rsaK);
char *pEncode = new char[nLen + 1];
int ret = RSA_public_encrypt(data.length(), (const unsigned char*)data.c_str(),
(unsigned char *)pEncode, rsaK, RSA_PKCS1_PADDING);
std::string strRet;
if (ret >= 0) {
strRet = std::string(pEncode, ret);
}
delete[] pEncode;
CRYPTO_cleanup_all_ex_data();
BIO_free_all(bp);
RSA_free(rsaK);
return strRet;
}
3.私钥解密
string bio_read_privateKey(string data) {
OpenSSL_add_all_algorithms();
BIO* bp = BIO_new(BIO_s_file());
BIO_read_filename(bp, "private.pem");
RSA* rsaK = PEM_read_bio_RSAPrivateKey(bp,