tg_rsa.h


// 注意: 编译mbedtls时, 添加宏 MBEDTLS_RSA_NO_CRT (基于 mbedtls 2.16.1) #ifndef _BVR_OPENSSL_H_ #define _BVR_OPENSSL_H_ #include <iostream> #include <string> typedef struct mbedtls_rsa_context RSA; bool tg_rsa_init(); bool tg_rsa_deinit(); // 生成密钥 bits >= 512 bool tg_rsa_key_generate(RSA** rsa, int bits); // 密钥转为字符串 bool tg_rsa_key_string(RSA* rsa, std::string& n, std::string& e, std::string& d); // 字符串转换为密钥 bool tg_rsa_key_get(RSA** rsa, const std::string& n, const std::string& e, const std::string& d = ""); // 释放rsa bool tg_rsa_key_free(RSA* rsa); // 密钥加密 usePubKey: 是否使用公钥加密 bool tg_rsa_encrypt(bool usePubKey, RSA* encrypt, std::string src, std::string& dst); // 密钥解密 usePriKey: 是否使用私钥加密 bool tg_rsa_decrypt(bool usePriKey, RSA* decrypt, std::string src, std::string& dst); /** base64 编码 */ std::string tg_base64_encode(const std::string& str_data); /** base64 解码 */ std::string tg_base64_decode(const std::string& str_encoded); /** aes cbc 加密 */ int tg_aes_cbc_encrypt(const std::string& plaintext, const std::string& key, const std::string& iv, std::string& ciphertext); /** aes cbc 解密 */ int tg_aes_cbc_decrypt(const std::string& ciphertext, const std::string& key, const std::string& iv, std::string& plaintext); /** 计算数据MD5值*/ std::string tg_md5_encode(const std::string& data); #endif //_BVR_OPENSSL_H_
tg_rsa.cpp


#include "tg_rsa.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mbedtls/config.h" #include "mbedtls/platform.h" #include "mbedtls/rsa.h" #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/error.h" #include "mbedtls/base64.h" #include "mbedtls/md5.h" #ifdef _MSC_VER #include <Windows.h> #pragma comment(lib, "mbedcrypto.lib") #pragma comment(lib, "mbedtls.lib") #pragma comment(lib, "mbedx509.lib") #endif #define EXPONENT 65537 mbedtls_entropy_context m_entropy; mbedtls_ctr_drbg_context m_ctr_drbg; bool tg_rsa_init() { const char *pers = "rsa_encrypt"; int ret = -1; mbedtls_ctr_drbg_init(&m_ctr_drbg); mbedtls_entropy_init(&m_entropy); ret = mbedtls_ctr_drbg_seed(&m_ctr_drbg, mbedtls_entropy_func, &m_entropy, (const unsigned char *)pers, strlen(pers)); return true; } bool tg_rsa_deinit() { mbedtls_ctr_drbg_free(&m_ctr_drbg); mbedtls_entropy_free(&m_entropy); return true; } bool tg_rsa_key_generate(RSA** pp_rsa, int bits) { mbedtls_rsa_context* p_rsa = NULL; int ret = -1; if (NULL == pp_rsa) { return false; } p_rsa = (mbedtls_rsa_context*)malloc(sizeof(mbedtls_rsa_context)); mbedtls_rsa_init(p_rsa, MBEDTLS_RSA_PKCS_V15, 0); ret = mbedtls_rsa_gen_key(p_rsa, mbedtls_ctr_drbg_random, &m_ctr_drbg, bits,