Base64算法及C++实现

Base64用途

1. 用于对 SOHO 级路由器(网关设备)管理员帐户密码的加密

2. 流媒体网站对于播放的流媒体文件的路径的加密

3. 迅雷等下载软件对下载链接地址的加密

Base64算法

Base64编码要求把38位字节(3*8=24)转化为46位的字节(4*6=24),之后在6位的前面补两个0,形成8位一个字节的形式。


Base64

函数:

unsigned intCreateMatchingEncodingBuffer (unsigned intp_InputByteCount,char**p_ppEncodingBuffer);

创建匹配于编码的缓存空间。参数:1输入字节数,2进行编码需要的缓存空间;返回值:缓存空间大小。

unsigned intCreateMatchingDecodingBuffer (char*p_pInputBufferString,char**p_ppDecodingBuffer);

创建匹配于解码的缓存空间。参数:1解码对象缓存,2进行解码需要的缓存空间;返回值:缓存空间大小。

voidEncodeBuffer (char*p_pInputBuffer,unsigned intp_InputBufferLength,char*p_pOutputBufferString);

进行编码。参数:1明文,2明文长度,3密文输出。

unsigned int DecodeBuffer (char*p_pInputBufferString,char*p_pOutputBuffer);

进行解码。参数:1密文,2明文;返回值:明文长度

C++实现:

[cpp]  view plain copy
  1. /************************************************ 
  2. *                       * 
  3. * CBase64.h                 * 
  4. * Base 64 de- and encoding class        * 
  5. *                       * 
  6. * ============================================  * 
  7. *                       * 
  8. * This class was written on 28.05.2003      * 
  9. * by Jan Raddatz [[email protected]]       * 
  10. *                       * 
  11. * ============================================  * 
  12. *                       * 
  13. * Copyright (c) by Jan Raddatz          * 
  14. * This class was published @ codeguru.com   * 
  15. * 28.05.2003                    * 
  16. *                       * 
  17. ************************************************/  
  18.   
  19. #pragma once  
  20.   
  21. #include <afx.h>  
  22. #include <stdlib.h>  
  23. #include <math.h>  
  24. #include <memory.h>  
  25. const static unsigned int MAX_LINE_LENGTH = 76;  
  26.   
  27. const static char BASE64_ALPHABET [64] =   
  28. {  
  29.     'A''B''C''D''E''F''G''H''I''J'//   0 -   9  
  30.     'K''L''M''N''O''P''Q''R''S''T'//  10 -  19  
  31.     'U''V''W''X''Y''Z''a''b''c''d'//  20 -  29  
  32.     'e''f''g''h''i''j''k''l''m''n'//  30 -  39  
  33.     'o''p''q''r''s''t''u''v''w''x'//  40 -  49  
  34.     'y''z''0''1''2''3''4''5''6''7'//  50 -  59  
  35.     '8''9''+''/'                //  60 -  63  
  36. };  
  37.   
  38. const static char BASE64_DEALPHABET [128] =   
  39. {  
  40.     0,  0,  0,  0,  0,  0,  0,  0,  0,  0, //   0 -   9  
  41.     0,  0,  0,  0,  0,  0,  0,  0,  0,  0, //  10 -  19  
  42.     0,  0,  0,  0,  0,  0,  0,  0,  0,  0, //  20 -  29  
  43.     0,  0,  0,  0,  0,  0,  0,  0,  0,  0, //  30 -  39  
  44.     0,  0,  0, 62,  0,  0,  0, 63, 52, 53, //  40 -  49  
  45.     54, 55, 56, 57, 58, 59, 60, 61,  0,  0, //  50 -  59  
  46.     0, 61,  0,  0,  0,  0,  1,  2,  3,  4, //  60 -  69  
  47.     5,  6,  7,  8,  9, 10, 11, 12, 13, 14, //  70 -  79  
  48.     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, //  80 -  89  
  49.     25,  0,  0,  0,  0,  0,  0, 26, 27, 28, //  90 -  99  
  50.     29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // 100 - 109  
  51.     39, 40, 41, 42, 43, 44, 45, 46, 47, 48, // 110 - 119  
  52.     49, 50, 51,  0,  0,  0,  0,  0      // 120 - 127  
  53. };  
  54.   
  55. enum  
  56. {  
  57.     UNABLE_TO_OPEN_INPUT_FILE,  
  58.     UNABLE_TO_OPEN_OUTPUT_FILE,  
  59.     UNABLE_TO_CREATE_OUTPUTBUFFER  
  60. };  
  61.   
  62. class CBase64  
  63. {  
  64. public:  
  65.     CBase64 ();  
  66.   
  67.     unsigned int CalculateRecquiredEncodeOutputBufferSize (unsigned int p_InputByteCount);  
  68.     unsigned int CalculateRecquiredDecodeOutputBufferSize (char* p_pInputBufferString);  
  69.   
  70.     void EncodeByteTriple  (char* p_pInputBuffer, unsigned int InputCharacters, char* p_pOutputBuffer);  
  71.     unsigned int DecodeByteQuartet (char* p_pInputBuffer, char* p_pOutputBuffer);  
  72.   
  73.     void EncodeBuffer (char* p_pInputBuffer, unsigned int p_InputBufferLength, char*p_pOutputBufferString);  
  74.     unsigned int DecodeBuffer (char* p_pInputBufferString, char* p_pOutputBuffer);  
  75.   
  76.     unsigned int CreateMatchingEncodingBuffer (unsigned int p_InputByteCount, char** p_ppEncodingBuffer);  
  77.     unsigned int CreateMatchingDecodingBuffer (char* p_pInputBufferString, char** p_ppDecodingBuffer);  
  78.   
  79.     unsigned int EncodeFile (char* p_pSourceFileName, char* p_pEncodedFileName);  
  80.     unsigned int DecodeFile (char* p_pSourceFileName, char* p_pDecodedFileName);  
  81. };  

[cpp]  view plain copy
  1. /************************************************ 
  2. *                       * 
  3. * CBase64.cpp                   * 
  4. * Base 64 de- and encoding class        * 
  5. *                       * 
  6. * ============================================  * 
  7. *                       * 
  8. * This class was written on 28.05.2003      * 
  9. * by Jan Raddatz [[email protected]]       * 
  10. *                       * 
  11. * ============================================  * 
  12. *                       * 
  13. * Copyright (c) by Jan Raddatz          * 
  14. * This class was published @ codeguru.com   * 
  15. * 28.05.2003                    * 
  16. *                       * 
  17. ************************************************/  
  18. #include "stdafx.h"  
  19. #include "CBase64.h"  
  20.   
  21.   
  22. CBase64::CBase64 ()  
  23. {  
  24. }  
  25.   
  26. unsigned int CBase64::CalculateRecquiredEncodeOutputBufferSize (unsigned int p_InputByteCount)  
  27. {  
  28.     div_t result = div (p_InputByteCount, 3);  
  29.   
  30.     unsigned int RecquiredBytes = 0;  
  31.     if (result.rem == 0)  
  32.     {  
  33.         // Number of encoded characters  
  34.         RecquiredBytes = result.quot * 4;  
  35.   
  36.         // CRLF -> "\r\n" each 76 characters  
  37.         result = div (RecquiredBytes, 76);  
  38.         RecquiredBytes += result.quot * 2;  
  39.   
  40.         // Terminating null for the Encoded String  
  41.         RecquiredBytes += 1;  
  42.   
  43.         return RecquiredBytes;  
  44.     }  
  45.     else  
  46.     {  
  47.         // Number of encoded characters  
  48.         RecquiredBytes = result.quot * 4 + 4;  
  49.   
  50.         // CRLF -> "\r\n" each 76 characters  
  51.         result = div (RecquiredBytes, 76);  
  52.         RecquiredBytes += result.quot * 2;  
  53.   
  54.         // Terminating null for the Encoded String  
  55.         RecquiredBytes += 1;  
  56.   
  57.         return RecquiredBytes;  
  58.     }  
  59. }  
  60.   
  61. unsigned int CBase64::CalculateRecquiredDecodeOutputBufferSize (char* p_pInputBufferString)  
  62. {  
  63.     unsigned int BufferLength = strlen (p_pInputBufferString);  
  64.   
  65.     div_t result = div (BufferLength, 4);  
  66.   
  67.     if (p_pInputBufferString [BufferLength - 1] != '=')  
  68.     {  
  69.         return result.quot * 3;  
  70.     }  
  71.     else  
  72.     {  
  73.         if (p_pInputBufferString [BufferLength - 2] == '=')  
  74.         {  
  75.             return result.quot * 3 - 2;  
  76.         }  
  77.         else  
  78.         {  
  79.             return result.quot * 3 - 1;  
  80.         }  
  81.     }  
  82. }  
  83.   
  84. void CBase64::EncodeByteTriple (char* p_pInputBuffer, unsigned int InputCharacters, char* p_pOutputBuffer)  
  85. {  
  86.     unsigned int mask = 0xfc000000;  
  87.     unsigned int buffer = 0;  
  88.   
  89.   
  90.     char* temp = (char*) &buffer;  
  91.     temp [3] = p_pInputBuffer [0];  
  92.     if (InputCharacters > 1)  
  93.         temp [2] = p_pInputBuffer [1];  
  94.     if (InputCharacters > 2)  
  95.         temp [1] = p_pInputBuffer [2];  
  96.   
  97.     switch (InputCharacters)  
  98.     {  
  99.     case 3:  
  100.         {  
  101.             p_pOutputBuffer [0] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  102.             buffer = buffer << 6;  
  103.             p_pOutputBuffer [1] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  104.             buffer = buffer << 6;  
  105.             p_pOutputBuffer [2] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  106.             buffer = buffer << 6;  
  107.             p_pOutputBuffer [3] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  108.             break;  
  109.         }  
  110.     case 2:  
  111.         {  
  112.             p_pOutputBuffer [0] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  113.             buffer = buffer << 6;  
  114.             p_pOutputBuffer [1] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  115.             buffer = buffer << 6;  
  116.             p_pOutputBuffer [2] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  117.             p_pOutputBuffer [3] = '=';  
  118.             break;  
  119.         }  
  120.     case 1:  
  121.         {  
  122.             p_pOutputBuffer [0] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  123.             buffer = buffer << 6;  
  124.             p_pOutputBuffer [1] = BASE64_ALPHABET [(buffer & mask) >> 26];  
  125.             p_pOutputBuffer [2] = '=';  
  126.             p_pOutputBuffer [3] = '=';  
  127.             break;  
  128.         }  
  129.     }  
  130. }  
  131.   
  132. unsigned int CBase64::DecodeByteQuartet (char* p_pInputBuffer, char* p_pOutputBuffer)  
  133. {  
  134.     unsigned int buffer = 0;  
  135.   
  136.     if (p_pInputBuffer[3] == '=')  
  137.     {  
  138.         if (p_pInputBuffer[2] == '=')  
  139.         {  
  140.             buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[0]]) << 6;  
  141.             buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[1]]) << 6;  
  142.             buffer = buffer << 14;  
  143.   
  144.             char* temp = (char*) &buffer;  
  145.             p_pOutputBuffer [0] = temp [3];  
  146.   
  147.             return 1;  
  148.         }  
  149.         else  
  150.         {  
  151.             buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[0]]) << 6;  
  152.             buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[1]]) << 6;  
  153.             buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[2]]) << 6;  
  154.             buffer = buffer << 8;  
  155.   
  156.             char* temp = (char*) &buffer;  
  157.             p_pOutputBuffer [0] = temp [3];  
  158.             p_pOutputBuffer [1] = temp [2];  
  159.   
  160.             return 2;  
  161.         }  
  162.     }  
  163.     else  
  164.     {  
  165.         buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[0]]) << 6;  
  166.         buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[1]]) << 6;  
  167.         buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[2]]) << 6;  
  168.         buffer = (buffer | BASE64_DEALPHABET [p_pInputBuffer[3]]) << 6;   
  169.         buffer = buffer << 2;  
  170.   
  171.         char* temp = (char*) &buffer;  
  172.         p_pOutputBuffer [0] = temp [3];  
  173.         p_pOutputBuffer [1] = temp [2];  
  174.         p_pOutputBuffer [2] = temp [1];  
  175.   
  176.         return 3;  
  177.     }  
  178.   
  179.     return -1;  
  180. }  
  181.   
  182. void CBase64::EncodeBuffer(char* p_pInputBuffer, unsigned int p_InputBufferLength, char* p_pOutputBufferString)  
  183. {  
  184.     unsigned int FinishedByteQuartetsPerLine = 0;  
  185.     unsigned int InputBufferIndex  = 0;  
  186.     unsigned int OutputBufferIndex = 0;  
  187.   
  188.     memset (p_pOutputBufferString, 0, CalculateRecquiredEncodeOutputBufferSize (p_InputBufferLength));  
  189.   
  190.     while (InputBufferIndex < p_InputBufferLength)  
  191.     {  
  192.         if (p_InputBufferLength - InputBufferIndex <= 2)  
  193.         {  
  194.             FinishedByteQuartetsPerLine ++;  
  195.             EncodeByteTriple (p_pInputBuffer + InputBufferIndex, p_InputBufferLength - InputBufferIndex, p_pOutputBufferString + OutputBufferIndex);  
  196.             break;  
  197.         }  
  198.         else  
  199.         {  
  200.             FinishedByteQuartetsPerLine++;  
  201.             EncodeByteTriple (p_pInputBuffer + InputBufferIndex, 3, p_pOutputBufferString + OutputBufferIndex);  
  202.             InputBufferIndex  += 3;  
  203.             OutputBufferIndex += 4;  
  204.         }  
  205.   
  206.         if (FinishedByteQuartetsPerLine == 19)  
  207.         {  
  208.             p_pOutputBufferString [OutputBufferIndex  ] = '\r';  
  209.             p_pOutputBufferString [OutputBufferIndex+1] = '\n';  
  210.             p_pOutputBufferString += 2;  
  211.             FinishedByteQuartetsPerLine = 0;  
  212.         }  
  213.     }  
  214. }  
  215.   
  216. unsigned int CBase64::DecodeBuffer (char* p_pInputBufferString, char* p_pOutputBuffer)  
  217. {  
  218.     unsigned int InputBufferIndex  = 0;  
  219.     unsigned int OutputBufferIndex = 0;  
  220.     unsigned int InputBufferLength = strlen (p_pInputBufferString);  
  221.   
  222.     char ByteQuartet [4];  
  223.   
  224.     while (InputBufferIndex < InputBufferLength)  
  225.     {  
  226.         for (int i = 0; i < 4; i++)  
  227.         {  
  228.             ByteQuartet [i] = p_pInputBufferString [InputBufferIndex];  
  229.   
  230.             // Ignore all characters except the ones in BASE64_ALPHABET  
  231.             if ((ByteQuartet [i] >= 48 && ByteQuartet [i] <=  57) ||  
  232.                 (ByteQuartet [i] >= 65 && ByteQuartet [i] <=  90) ||  
  233.                 (ByteQuartet [i] >= 97 && ByteQuartet [i] <= 122) ||  
  234.                 ByteQuartet [i] == '+' || ByteQuartet [i] == '/' || ByteQuartet [i] == '=')  
  235.             {  
  236.             }  
  237.             else  
  238.             {  
  239.                 // Invalid character  
  240.                 i--;  
  241.             }  
  242.   
  243.             InputBufferIndex++;  
  244.         }  
  245.   
  246.         OutputBufferIndex += DecodeByteQuartet (ByteQuartet, p_pOutputBuffer + OutputBufferIndex);  
  247.     }  
  248.   
  249.     // OutputBufferIndex gives us the next position of the next decoded character  
  250.     // inside our output buffer and thus represents the number of decoded characters  
  251.     // in our buffer.  
  252.     return OutputBufferIndex;  
  253. }  
  254.   
  255. unsigned int CBase64::CreateMatchingEncodingBuffer (unsigned int p_InputByteCount, char** p_ppEncodingBuffer)  
  256. {  
  257.     unsigned int Size = CalculateRecquiredEncodeOutputBufferSize (p_InputByteCount);  
  258.     (*p_ppEncodingBuffer) = (char*) malloc (Size);  
  259.     memset (*p_ppEncodingBuffer, 0, Size);  
  260.     return Size;  
  261. }  
  262.   
  263. unsigned int CBase64::CreateMatchingDecodingBuffer (char* p_pInputBufferString, char** p_ppDecodingBuffer)  
  264. {  
  265.     unsigned int Size = CalculateRecquiredDecodeOutputBufferSize (p_pInputBufferString);  
  266.     (*p_ppDecodingBuffer) = (char*) malloc (Size+1);  
  267.     memset (*p_ppDecodingBuffer, 0, Size+1);  
  268.     return Size+1;  
  269. }  
  270.   
  271. unsigned int CBase64::EncodeFile (char* p_pSourceFileName, char* p_pEncodedFileName)  
  272. {  
  273.     CFile InputFile;  
  274.     CFile OutputFile;  
  275.   
  276.     if (!InputFile.Open (p_pSourceFileName, CFile::modeRead))  
  277.         return UNABLE_TO_OPEN_INPUT_FILE;  
  278.   
  279.     if (!OutputFile.Open (p_pEncodedFileName, CFile::modeCreate|CFile::modeWrite))  
  280.         return UNABLE_TO_OPEN_OUTPUT_FILE;  
  281.   
  282.     char InputBuffer [19 * 3];  
  283.     char* pOutputBuffer;  
  284.     CreateMatchingEncodingBuffer (sizeof (InputBuffer), &pOutputBuffer);  
  285.   
  286.     if (pOutputBuffer == 0)  
  287.         return UNABLE_TO_CREATE_OUTPUTBUFFER;  
  288.   
  289.     unsigned int ReadBytes = 0;  
  290.     while ((ReadBytes = InputFile.Read (InputBuffer, sizeof (InputBuffer))) != 0)  
  291.     {  
  292.         EncodeBuffer (InputBuffer, ReadBytes, pOutputBuffer);  
  293.         OutputFile.Write (pOutputBuffer, strlen (pOutputBuffer));  
  294.     }  
  295.   
  296.     OutputFile.Flush ();  
  297.     OutputFile.Close ();  
  298.     InputFile.Close  ();  
  299.   
  300.     return 0;  
  301. }  
  302.   
  303. unsigned int CBase64::DecodeFile (char* p_pSourceFileName, char* p_pDecodedFileName)  
  304. {  
  305.     CStdioFile  InputFile;  
  306.     CFile       OutputFile;  
  307.   
  308.     if (!InputFile.Open (p_pSourceFileName, CFile::modeRead))  
  309.         return UNABLE_TO_OPEN_INPUT_FILE;  
  310.   
  311.     if (!OutputFile.Open (p_pDecodedFileName, CFile::modeCreate|CFile::modeWrite))  
  312.         return UNABLE_TO_OPEN_OUTPUT_FILE;  
  313.   
  314.     CString InputBuffer;  
  315.     char    OutputBuffer[64];  
  316.   
  317.     unsigned int ReadBytes = 0;  
  318.     while ((ReadBytes = InputFile.ReadString (InputBuffer)) != 0)  
  319.     {  
  320.         InputBuffer.Remove ('\r');  
  321.         InputBuffer.Remove ('\n');  
  322.         unsigned int DecodedBytes = DecodeBuffer ((LPTSTR) (LPCTSTR) InputBuffer, OutputBuffer);  
  323.         OutputFile.Write (&OutputBuffer [0], DecodedBytes);  
  324.     }  
  325.   
  326.     OutputFile.Flush ();  
  327.     OutputFile.Close ();  
  328.     InputFile.Close  ();  
  329.   
  330.     return 0;  
  331. }  

转载自:http://blog.csdn.net/luxiaoxun/article/details/7641338

参考网站:

1.Base64-维基百科( http://zh.wikipedia.org/wiki/Base64
2. BASE 64 Decoding and Encoding Class2003  (http://www.codeguru.com/cpp/cpp/algorithms/article.php/c5099 )

猜你喜欢

转载自blog.csdn.net/jusang486/article/details/43559665