Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1097081
  • 博文数量: 80
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 746
  • 用 户 组: 普通用户
  • 注册时间: 2018-06-12 20:01
个人简介

寫写code、调調bug、填填坑,僅此而已。

文章分类

全部博文(80)

文章存档

2019年(30)

2018年(50)

分类: C/C++

2018-09-13 14:00:31

1.安装openssl包
   sudo apt-get install openssl
   sudo apt-get install libssl-dev
借鉴csdn大神代码,进行了改写,调试
2.tools.h文件

点击(此处)折叠或打开

  1. #ifndef TOOLS_H
  2. #define TOOLS_H
  3. #include<openssl/rsa.h>
  4. #include <openssl/bio.h>
  5. #include<openssl/pem.h>
  6. #include<openssl/err.h>
  7. #include<iostream>
  8. using namespace std;

  9. static const std::string base64_chars =
  10.              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  11.              "abcdefghijklmnopqrstuvwxyz"
  12.              "0123456789+/";

  13. static inline bool is_base64(unsigned char c) {
  14.   return (isalnum(c) || (c == '+') || (c == '/'));
  15. }



  16. static RSA* GetKeyRSA(std::string strKey,const int type)//type = 1 公钥 type = 2 私钥
  17. {
  18.     int nPublicKeyLen = strKey.size(); //strKey为base64编码的公钥字符串
  19.     for(int i = 64; i < nPublicKeyLen; i+=64)
  20.     {
  21.         if(strKey[i] != '\n')
  22.         {
  23.             strKey.insert(i, "\n");
  24.         }
  25.         i++;
  26.     }
  27.     if(type == 1){
  28.         strKey.insert(0, "-----BEGIN PUBLIC KEY-----\n");
  29.         strKey.append("\n-----END PUBLIC KEY-----\n");
  30.     }else{
  31.         strKey.insert(0, "-----BEGIN PRIVATE KEY-----\n");
  32.         strKey.append("\n-----END PRIVATE KEY-----\n");
  33.     }

  34.     BIO *bio = NULL;
  35.     RSA *rsa = NULL;
  36.     char *chPublicKey = const_cast<char *>(strKey.c_str());
  37.     printf("chPublicKey===%s\n",chPublicKey);
  38.     if ((bio = BIO_new_mem_buf(chPublicKey, -1)) == NULL) //从字符串读取RSA公钥
  39.     {
  40.             return NULL;
  41.     }
  42.     if(type == 1)
  43.         rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL); //从bio结构中得到rsa结构
  44. // rsa = PEM_read_bio_RSAPublicKey(bio,&rsa,NULL,NULL);
  45.     else
  46.         rsa = PEM_read_bio_RSAPrivateKey(bio,NULL,NULL,NULL);
  47.     if (NULL == rsa)
  48.     {
  49.         BIO_free_all(bio);
  50.         unsigned long ulErr = ERR_get_error(); // 获取错误号
  51.         char szErrMsg[1024] = {0};
  52.         char *pTmp = NULL;
  53.         pTmp = ERR_error_string(ulErr,szErrMsg); // 格式:error:errId::函数:原因
  54.         cout << szErrMsg;
  55.         cout << "load public key fail error=" <<ulErr << " msg=" << szErrMsg;
  56.     }
  57.     else
  58.     {
  59.         cout<< "load public key ok "<<endl;
  60.     }
  61.     return rsa;
  62. }


  63. static std::string base64_decode(std::string const& encoded_string) {
  64.   int in_len = encoded_string.size();
  65.   int i = 0;
  66.   int j = 0;
  67.   int in_ = 0;
  68.   unsigned char char_array_4[4], char_array_3[3];
  69.   std::string ret;

  70.   while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  71.     char_array_4[i++] = encoded_string[in_]; in_++;
  72.     if (i ==4) {
  73.       for (i = 0; i <4; i++)
  74.         char_array_4[i] = base64_chars.find(char_array_4[i]);

  75.       char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  76.       char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  77.       char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

  78.       for (i = 0; (i < 3); i++)
  79.         ret += char_array_3[i];
  80.       i = 0;
  81.     }
  82.   }
  83.   if (i) {
  84.     for (j = i; j <4; j++)
  85.       char_array_4[j] = 0;

  86.     for (j = 0; j <4; j++)
  87.       char_array_4[j] = base64_chars.find(char_array_4[j]);

  88.     char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  89.     char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  90.     char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

  91.     for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  92.   }

  93.   return ret;
  94. }


  95. static char* base64Encode(char const* origSigned, unsigned origLength)
  96. {
  97.     unsigned int numOrig24BitValues = 0;
  98.     unsigned int numResultBytes = 0;
  99.     int havePadding = 0;
  100.     int havePadding2 = 0;
  101.     char* result = NULL;
  102.     unsigned int i = 0;


  103.     unsigned char const* orig = (unsigned char const*)origSigned; // in case any input bytes have the MSB set
  104.     if (orig == NULL) return NULL;

  105.     numOrig24BitValues = origLength / 3;
  106.     havePadding = origLength > numOrig24BitValues * 3;
  107.     havePadding2 = origLength == numOrig24BitValues * 3 + 2;
  108.     numResultBytes = 4 * (numOrig24BitValues + havePadding);
  109.     result = (char*)malloc(numResultBytes + 1); // allow for trailing '/0'

  110.                                                  // Map each full group of 3 input bytes into 4 output base-64 characters:

  111.     for (i = 0; i < numOrig24BitValues; ++i)
  112.     {
  113.         result[4 * i + 0] = base64_chars[(orig[3 * i] >> 2) & 0x3F];
  114.         result[4 * i + 1] = base64_chars[(((orig[3 * i] & 0x3) << 4) | (orig[3 * i + 1] >> 4)) & 0x3F];
  115.         result[4 * i + 2] = base64_chars[((orig[3 * i + 1] << 2) | (orig[3 * i + 2] >> 6)) & 0x3F];
  116.         result[4 * i + 3] = base64_chars[orig[3 * i + 2] & 0x3F];
  117.     }

  118.     // Now, take padding into account. (Note: i == numOrig24BitValues)
  119.     if (havePadding)
  120.     {
  121.         result[4 * i + 0] = base64_chars[(orig[3 * i] >> 2) & 0x3F];
  122.         if (havePadding2)
  123.         {
  124.             result[4 * i + 1] = base64_chars[(((orig[3 * i] & 0x3) << 4) | (orig[3 * i + 1] >> 4)) & 0x3F];
  125.             result[4 * i + 2] = base64_chars[(orig[3 * i + 1] << 2) & 0x3F];
  126.         }
  127.         else
  128.         {
  129.             result[4 * i + 1] = base64_chars[((orig[3 * i] & 0x3) << 4) & 0x3F];
  130.             result[4 * i + 2] = '=';
  131.         }
  132.         result[4 * i + 3] = '=';
  133.     }

  134.     result[numResultBytes] = (char)('/0');
  135.     return result;

  136. }

  137. #endif // TOOLS_H
2.verify.h

点击(此处)折叠或打开

  1. #include "tools.h"
  2. char* rsa_sign(const char* privateKey,const char* content);
  3. bool rsa_verify(const char* publicKey,const char* sign,const char* content);
  4. char* EncryData(const char* publicKey,const char* content);
  5. void DecryData(const char* privateKey,const char* content);
3.verify.c

点击(此处)折叠或打开

  1. #include "rsapro.h"
  2. #include<string.h>
  3. char *rsa_sign(const char *privateKey, const char *content)
  4. {
  5.      char p_sign[10000] = {0};
  6.      RSA *p_rsa = GetKeyRSA(privateKey,2);
  7.      int rsa_len = RSA_size(p_rsa);
  8.      if(RSA_sign(NID_md5,(unsigned char*)content,strlen(content),(unsigned char*)p_sign,(unsigned int *)&rsa_len,p_rsa)<0){
  9.          cout<<"RSA_SIGN FAILED"<<endl;
  10.          return "";
  11.      }
  12.     RSA_free(p_rsa);
  13.     char *sign = base64Encode(p_sign,rsa_len);
  14.     cout<<"sign===="<<sign<<endl;
  15.     return sign;


  16. }

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

  19.     char p_ver[1000] = {0};
  20.     RSA *p_rsa = GetKeyRSA(publicKey,1);
  21.     int rsa_len = RSA_size(p_rsa);
  22.     std::string dSign = base64_decode(sign);
  23.     int res = RSA_verify(NID_md5,(unsigned char*)content,strlen(content) ,(unsigned char*)dSign.c_str(),dSign.length() ,p_rsa);
  24.     RSA_free(p_rsa);
  25.     return res == 1;
  26. }

  27. char* EncryData(const char *publicKey, const char *content)
  28. {

  29.     RSA *p_rsa = GetKeyRSA(publicKey,1);
  30.     int rsa_len = RSA_size(p_rsa);
  31.     char p_e[1000] = {0};

  32.     if(RSA_public_encrypt(strlen(content), (unsigned char *)content, (unsigned char*)p_e, p_rsa, RSA_PKCS1_PADDING)<0) {
  33.         cout<<"RSA_public_encrypt err"<<endl;
  34.         return NULL;
  35.     }

  36.     while (true) {
  37.         if(strlen(p_e) == 128){
  38.               break;
  39.         }
  40.         if(RSA_public_encrypt(strlen(content), (unsigned char *)content, (unsigned char*)p_e, p_rsa, RSA_PKCS1_PADDING)<0)
  41.             cout<<"RSA_public_encrypt err"<<endl;

  42.     }
  43.     RSA_free(p_rsa);
  44.     char * bp_e = base64Encode(p_e,rsa_len);
  45.     cout<<"encrydate====="<<bp_e<<endl;
  46.     return bp_e;

  47. }

  48. void DecryData(const char *privateKey, const char *content)
  49. {

  50.     RSA *p_rsa = GetKeyRSA(privateKey,2);
  51.     int rsa_len = RSA_size(p_rsa);
  52.     char p_de[1000] = {0};
  53.     std::string unBase64 = base64_decode(content);
  54.      if (RSA_private_decrypt(unBase64.length(), (unsigned char *)unBase64.c_str(), (unsigned char*)p_de, p_rsa, RSA_PKCS1_PADDING)<0) {//RSA_PKCS1_PADDING
  55.          cout<<"RSA_private_decrypt err"<<endl;
  56.          return ;
  57.      }
  58.      RSA_free(p_rsa);
  59.     cout<<"RSA_private_decrypt:"<<p_de<<endl;
  60. }
4.main.c

点击(此处)折叠或打开

  1. #include "verify.h"
  2. #include<string.h>
  3. int main(int argc, char *argv[])
  4. {
  5.   printf("test main.....\n");
  6.   char *publicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqfi52bS5eBwlVUxmtj2h6r47S8nxWzEkMS4aAS8W/PBkubAHi3OZk/ty8cnca3U4wW2P6fOtho3IcYlHAbZ0nGgLr9YzW8Qjf5/oG478QP1T2ikRyAd8xzh+9A4RUYJxxpTqpQkbz47OiB0zCCH2zVrgYhqKl5U6q70KD/ND4tNvjVW71tRfSM2A4EeJMfzydKa+Fh5vYsYBtPRKQijfVZ9LaGXUPTt++JNQ6yNEDhfYrh/CeOYbhFtUB8gQ4+UqzEEyucb5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H7P1hiyuBLIP8IoCZPnZBQjUa2SUzk1gd1bjWzO4dVe3HqIzvcnYFE8XBpFNybtpd9PyZOFSn24Fu/K1ZC3TKiaPksY20CgYBtVPewL+yvHNbP3r3pNcJuFNyfFJn012y/S0GewG0DtkXZyZkz8yqNr16vEYFmkEb718dgryQsRcF7plih3z+eAfVzXXIhQ9v47LhI03FHHqHnNtpjAOvmvFQPJu43h70oRapbhoYEC95Vo9rF+jlRaQJYs0s8cz8ekMo3Xe4eiwKBgC/2PShH8g0Z2AzL2jFQhia5vXUsFVFax9x1rXBsGLZEHSykYLGkZ4AitwnqPyJeHyMa2EGES1ISEKhtLsKyeDd5H1BbttcYS9jYQVDVzk1MBGnlJbM90hVK8xRDhol7+CovTN5dAVoktpPebU2t0eR135N/Omicks9sZSyhR+TFAoGAKNEja8gCdRl8wS970SNBwhlo6LePfeLtWnu3Ewxyo49cdGyZs0EdhiPYWRURpM+cvTu3JP9jD3sNsC2Et5o2uoFcG1ktraur2SESmkaXvfVnZTwiGe7gYjFaqvhp0gAVblv1iAABzr55YktvIu9vEW5Ia8FDOWoGTappV+Uj/ss=";
  8. char *verifystr="gxycloudtest";
  9.  printf("len==%s\n",strlen(privateKey));
  10. //rsa_sign(privateKey,verifystr);
  11.   return 0;
  12. }


阅读(5664) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~