前言:项目需要根据秘钥加密, 客户端根据公钥解密, 这里使用RSA加解密
在项目中导入openssl的动态链接库, libeay32.dll, libeay32.lib, 配置好工程环境, 代码:
/** * @author: HanshuaiWu * @methodsName: encrypt * @description: 签名 * @param1: orgData:原数据 * @param2: publicKey:公钥 * @return: AnsiString * @createTime: 2018/11/9 */extern "C" { AnsiString TIDCard::encrypt(AnsiString orgData) { //C:\Users\Administrator\Desktop\移动服务器v1.0网络请求\CardServerV2\Output\key.pem char *p_en = NULL; RSA *p_rsa = NULL; FILE *file = NULL; AnsiString pathStr = "key.pem"; char *path_key = (char *)pathStr.c_str(); int rsa_len = 0; //flen为源文件长度, rsa_len为秘钥长度 //1.打开秘钥文件 if((file = fopen(path_key, "r")) == NULL) { return-1; } BIO *in = NULL; in = BIO_new(BIO_s_file()); if( BIO_read_filename(in, path_key) != 1) { return -1; } if(in == NULL){ return -1; } p_rsa = PEM_read_bio_RSAPrivateKey(in , NULL, NULL, NULL); //3.获取秘钥的长度 rsa_len = RSA_size(p_rsa); //4.为加密后的内容 申请空间(根据秘钥的长度) p_en = (char *)malloc(rsa_len); if(!p_en) { return -1; } memset(p_en, 0, rsa_len); int length = orgData.Length(); char *orgBuffer = (char *) malloc(length);; orgBuffer = (char *)AnsiToUtf8(orgData).c_str(); int len = RSA_private_encrypt(strlen(orgBuffer), orgBuffer, p_en, p_rsa, RSA_PKCS1_PADDING); AnsiString result = Encode(p_en, len); // free free_all: fclose(file); BIO_free_all(in); RSA_free(p_rsa); free(p_en); free(orgBuffer); return result; } }// base64编码AnsiString TIDCard::Encode(const unsigned char* Data,int DataByte) { //编码表 const char EncodeTable[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; //返回值 AnsiString strEncode; unsigned char Tmp[4]={0}; int LineLength=0; for(int i=0;i<(int)(DataByte / 3);i++) { Tmp[1] = *Data++; Tmp[2] = *Data++; Tmp[3] = *Data++; strEncode+= EncodeTable[Tmp[1] >> 2]; strEncode+= EncodeTable[((Tmp[1] << 4) | (Tmp[2] >> 4)) & 0x3F]; strEncode+= EncodeTable[((Tmp[2] << 2) | (Tmp[3] >> 6)) & 0x3F]; strEncode+= EncodeTable[Tmp[3] & 0x3F]; if(LineLength+=4,LineLength==76) { //strEncode+="\r\n"; LineLength=0; } } //对剩余数据进行编码 int Mod=DataByte % 3; if(Mod==1) { Tmp[1] = *Data++; strEncode+= EncodeTable[(Tmp[1] & 0xFC) >> 2]; strEncode+= EncodeTable[((Tmp[1] & 0x03) << 4)]; strEncode+= "=="; } else if(Mod==2) { Tmp[1] = *Data++; Tmp[2] = *Data++; strEncode+= EncodeTable[(Tmp[1] & 0xFC) >> 2]; strEncode+= EncodeTable[((Tmp[1] & 0x03) << 4) | ((Tmp[2] & 0xF0) >> 4)]; strEncode+= EncodeTable[((Tmp[2] & 0x0F) << 2)]; strEncode+= "="; } return strEncode; }
作者:CoderW
链接:https://www.jianshu.com/p/8d9c6982b42f
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦