openssl的加解密,签名,验签代码

加密算法:

QString EncryData(const char *publicKey, const char *content)//publicKey:公钥,content:要加密的内容
{
      RSA *p_rsa = GetKeyRSA(publicKey,1);//将文本公钥转化成 RSA 对象
      int rsa_len = RSA_size(p_rsa);
      char p_e[1000] = {0};
      if(RSA_public_encrypt(strlen(content), (unsigned char *)content, (unsigned char*)p_e, p_rsa, RSA_PKCS1_PADDING)<0) {
          qDebug()<<"RSA_public_encrypt err";
          return "";
      }

      while (true) {RSA_PKCS1_PADDING 加密后是128的长度,不知道为什么有时加密长度不为128
          if(strlen(p_e) == 128){
                break;
          }
          if(RSA_public_encrypt(strlen(content), (unsigned char *)content, (unsigned char*)p_e, p_rsa, RSA_PKCS1_PADDING)<0)
              qDebug()<<"RSA_public_encrypt err";
          mSleep(50);
      }
      RSA_free(p_rsa);
      char * bp_e = base64Encode(p_e,rsa_len);
     return QString::fromLatin1(bp_e);



}
解密算法:

void DecryData(const char *privateKey,const char* content)
{
     qDebug()<<"------RSA_private_decrypt-------";
     RSA *p_rsa = GetKeyRSA(privateKey,2);
     int rsa_len = RSA_size(p_rsa);
     char p_de[1000] = {0};
     std::string unBase64 = base64_decode(content);
      if (RSA_private_decrypt(unBase64.length(), (unsigned char *)unBase64.c_str(), (unsigned char*)p_de, p_rsa, RSA_PKCS1_PADDING)<0) {//RSA_PKCS1_PADDING
          qDebug()<<"RSA_private_decrypt err";
          return ;
      }
      RSA_free(p_rsa);
     qDebug()<<"RSA_private_decrypt:"<<p_de;


}

私钥签名:

QString Widget::rsa_signA(const char *privateKey,const char* content){

     char p_sign[1000] = {0};
     RSA *p_rsa =  GetKeyRSA(privateKey,2);
     int rsa_len = RSA_size(p_rsa);
     if(RSA_sign(NID_md5,(unsigned char*)content,strlen(content),(unsigned char*)p_sign,(unsigned int *)&rsa_len,p_rsa)<0){
         qDebug()<<"RSA_SIGN FAILED";
         return "";
     }

    RSA_free(p_rsa);
    char *sign =  base64Encode(p_sign,rsa_len);
    qDebug()<<"sign:"<<sign;
	return QString::fromLatin1(sign);

}

公钥验签:

bool rsa_verify(const char *publicKey,const char* sign,const char *content)
{


    char p_ver[1000] = {0};
    RSA *p_rsa =  GetKeyRSA(publicKey,1);
    int rsa_len = RSA_size(p_rsa);
    std::string dSign = base64_decode(sign);


    int res = RSA_verify(NID_md5,(unsigned char*)content,strlen(content) ,(unsigned char*)dSign.c_str(),dSign.length() ,p_rsa);
    RSA_free(p_rsa);
    qDebug()<<"res:"<<res;
    if(res == 1){
     qDebug()<<"RSA_verify success:"<<res;
    }else{
         qDebug()<<"RSA_verify FAILED";
    }


    return res == 1;


}

代码下载地址:http://download.csdn.net/download/xzpblog/9986593

猜你喜欢

转载自blog.csdn.net/xzpblog/article/details/78036927