Base64加密解密原理以及代码实现

来源:互联网 发布:二手车统一发票软件 编辑:程序博客网 时间:2024/05/20 00:16
1. Base64使用A--Z,a--z,0--9,+,/ 这64个字符.
    2. 编码原理:将3个字节转换成4个字节( (3 X 8) = 24 = (4 X 6) )先读入3个字节,每读一个字节,左移8位,再右移四次,每次6位,这样就有4个字节了.
    3. 解码原理:将4个字节转换成3个字节.先读入4个6位(用或运算),每次左移6位,再右移3次,每次8位.这样就还原了.

    Base64是一种很常见的编码规范,其作用是将二进制序列转换为人类可读的ASCII字符序列,常用在需用通过文本协议(比如HTTP和SMTP)来传输二进制数据的情况下。Base64并不是一种用于安全领域的加密解密算法(这类算法有DES等),尽管我们有时也听到使用Base64来加密解密的说法,但这里所说的加密与解密实际是指编码(encode)和解码(decode)的过程,其变换是非常简单的,仅仅能够避免信息被直接识别。

   

    Base64采用了一种很简单的编码转换:对于待编码数据,以3个字节为单位,依次取6位数据并在前面补上两个0形成新的8位编码,由于3*8=4*6,这样3个字节的输入会变成4个字节的输出,长度上增加了1/3。

上面的处理还不能保证得到的字符都是可见字符,为了达到此目的,Base64制定了一个编码表,进行统一的转换。码表的大小为2^6=64,这也是Base64名称的由来。

                            Base64编码表

      Value Encoding  Value Encoding  Value Encoding  Value Encoding
           0 A            17 R            34 i            51 z
           1 B            18 S            35 j            52 0
           2 C            19 T            36 k            53 1
           3 D            20 U            37 l            54 2
           4 E            21 V            38 m           55 3
           5 F            22 W           39 n           56 4
           6 G            23 X            40 o            57 5
           7 H            24 Y             41 p            58 6
           8 I            25 Z             42 q            59 7
           9 J            26 a             43 r             60 8
          10 K            27 b            44 s            61 9
          11 L            28 c            45 t             62 +
          12 M            29 d           46 u            63 /
          13 N            30 e           47 v
          14 O            31 f            48 w         (pad) =
          15 P            32 g           49 x
          16 Q            33 h           50 y
         

    Base64编解码算法都很简单,网上有很多源码,这里就不介绍了。

 

    另外还有一点要注意的地方,前面提到编码是以3个字节为单位,当剩下的字符数量不足3个字节时,则应使用0进行填充,相应的,输出字符则使用'='占位,因此编码后输出的文本末尾可能会出现1至2个'='。

这是一种典型的编码转换的处理方法,类似的可能还有UTF16与UTF8之间的转换。 

[cpp] view plaincopy
  1. /** 
  2. * /file base64.h 
  3. */  
  4. #ifndef XYSSL_BASE64_H  
  5. #define XYSSL_BASE64_H  
  6.   
  7. #define XYSSL_ERR_BASE64_BUFFER_TOO_SMALL -0x0010  
  8. #define XYSSL_ERR_BASE64_INVALID_CHARACTER -0x0012  
  9.   
  10. #ifdef __cplusplus  
  11. extern "C" {  
  12. #endif  
  13.   
  14. /** 
  15. * /brief Encode a buffer into base64 format 
  16. * 
  17. * /param dst destination buffer 
  18. * /param dlen size of the buffer 
  19. * /param src source buffer 
  20. * /param slen amount of data to be encoded 
  21. * 
  22. * /return 0 if successful, or XYSSL_ERR_BASE64_BUFFER_TOO_SMALL. 
  23. * *dlen is always updated to reflect the amount 
  24. * of data that has (or would have) been written. 
  25. * 
  26. * /note Call this function with *dlen = 0 to obtain the 
  27. * required buffer size in *dlen 
  28. */  
  29. int base64_encode(const unsigned char *src, int slen,unsigned char *dst, int *dlen);  
  30.   
  31. /** 
  32. * /brief Decode a base64-formatted buffer 
  33. * 
  34. * /param dst destination buffer 
  35. * /param dlen size of the buffer 
  36. * /param src source buffer 
  37. * /param slen amount of data to be decoded 
  38. * 
  39. * /return 0 if successful, XYSSL_ERR_BASE64_BUFFER_TOO_SMALL, or 
  40. * XYSSL_ERR_BASE64_INVALID_DATA if the input data is not 
  41. * correct. *dlen is always updated to reflect the amount 
  42. * of data that has (or would have) been written. 
  43. * 
  44. * /note Call this function with *dlen = 0 to obtain the 
  45. * required buffer size in *dlen 
  46. */  
  47. int base64_decode(const unsigned char *src, int slen,unsigned char *dst, int *dlen);  
  48.   
  49. /** 
  50. * /brief Checkup routine 
  51. * 
  52. * /return 0 if successful, or 1 if the test failed 
  53. */  
  54. int base64_self_test( int verbose );  
  55.   
  56. #ifdef __cplusplus  
  57. }  
  58. #endif  
  59.   
  60. class CBase64    
  61. {  
  62. public:  
  63.     CBase64();  
  64.     virtual ~CBase64();  
  65.     static BOOL Encrypt(const unsigned char *pSrc,int iSlen,unsigned char *pDst,int *iDlen,CString &strErrorInfo);  
  66.     static BOOL Decrypt(const unsigned char *pSrc,int iSlen,unsigned char *pDst,int *iDlen,CString &strErrorInfo);  
  67. private:  
  68.   
  69. };  
  70.   
  71. #endif /* base64.h */  

 

[cpp] view plaincopy
  1. //source file: base64.cpp  
  2.   
  3. /* 
  4. * RFC 1521 base64 encoding/decoding 
  5. * 
  6. * Copyright (C) 2006-2007 Christophe Devine 
  7. * 
  8. * This library is free software; you can redistribute it and/or 
  9. * modify it under the terms of the GNU Lesser General Public 
  10. * License, version 2.1 as published by the Free Software Foundation. 
  11. * 
  12. * This library is distributed in the hope that it will be useful, 
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of 
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
  15. * Lesser General Public License for more details. 
  16. * 
  17. * You should have received a copy of the GNU Lesser General Public 
  18. * License along with this library; if not, write to the Free Software 
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
  20. * MA 02110-1301 USA 
  21. */  
  22. #include "stdafx.h"  
  23. #include "base64.h"  
  24.   
  25. static const unsigned char base64_enc_map[64] =  
  26. {  
  27. 'A''B''C''D''E''F''G''H''I''J',  
  28. 'K''L''M''N''O''P''Q''R''S''T',  
  29. 'U''V''W''X''Y''Z''a''b''c''d',  
  30. 'e''f''g''h''i''j''k''l''m''n',  
  31. 'o''p''q''r''s''t''u''v''w''x',  
  32. 'y''z''0''1''2''3''4''5''6''7',  
  33. '8''9''+''/'  
  34. };  
  35.   
  36. static const unsigned char base64_dec_map[128] =  
  37. {  
  38. 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,  
  39. 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,  
  40. 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,  
  41. 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,  
  42. 127, 127, 127, 62, 127, 127, 127, 63, 52, 53,  
  43. 54, 55, 56, 57, 58, 59, 60, 61, 127, 127,  
  44. 127, 64, 127, 127, 127, 0, 1, 2, 3, 4,  
  45. 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,  
  46. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,  
  47. 25, 127, 127, 127, 127, 127, 127, 26, 27, 28,  
  48. 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,  
  49. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,  
  50. 49, 50, 51, 127, 127, 127, 127, 127  
  51. };  
  52.   
  53. /* 
  54. * Encode a buffer into base64 format 
  55. */  
  56. int base64_encode(const unsigned char *src, int slen,unsigned char *dst, int *dlen)  
  57. {  
  58.     int i, n;  
  59.     int C1, C2, C3;  
  60.     unsigned char *p;  
  61.   
  62.     if( slen == 0 )  
  63.     return( 0 );  
  64.   
  65.     n = (slen << 3) / 6;  
  66.   
  67.     switch( (slen << 3) - (n * 6) )  
  68.     {  
  69.     case 2: n += 3; break;  
  70.     case 4: n += 2; break;  
  71.     defaultbreak;  
  72.     }  
  73.   
  74.     if( *dlen < n + 1 )  
  75.     {  
  76.         *dlen = n + 1;  
  77.         return( XYSSL_ERR_BASE64_BUFFER_TOO_SMALL );  
  78.     }  
  79.   
  80.     n = (slen / 3) * 3;  
  81.   
  82.     for( i = 0, p = dst; i < n; i += 3 )  
  83.     {  
  84.         C1 = *src++;  
  85.         C2 = *src++;  
  86.         C3 = *src++;  
  87.   
  88.         *p++ = base64_enc_map[(C1 >> 2) & 0x3F];  
  89.         *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];  
  90.         *p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F];  
  91.         *p++ = base64_enc_map[C3 & 0x3F];  
  92.     }  
  93.   
  94.     if( i < slen )  
  95.     {  
  96.         C1 = *src++;  
  97.         C2 = ((i + 1) < slen) ? *src++ : 0;  
  98.   
  99.         *p++ = base64_enc_map[(C1 >> 2) & 0x3F];  
  100.         *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];  
  101.   
  102.         if( (i + 1) < slen )  
  103.         *p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F];  
  104.         else *p++ = '=';  
  105.   
  106.         *p++ = '=';  
  107.     }  
  108.     *dlen =static_cast<int>(p - dst);  
  109.     *p = 0;  
  110.     return( 0 );  
  111. }  
  112.   
  113. /* 
  114. * Decode a base64-formatted buffer 
  115. */  
  116. int base64_decode(const unsigned char *src, int slen,unsigned char *dst, int *dlen)  
  117. {  
  118.     int i, j, n;  
  119.     unsigned long x;  
  120.     unsigned char *p;  
  121.   
  122.     for( i = j = n = 0; i < slen; i++ )  
  123.     {  
  124.         if( ( slen - i ) >= 2 &&  
  125.         *(src+i) == '/r' && *(src+i+1) == '/n' )  
  126.             continue;  
  127.   
  128.         if(*(src+i) == '/n' )  
  129.             continue;  
  130.   
  131.         if(*(src+i) == '=' && ++j > 2 )  
  132.             return( XYSSL_ERR_BASE64_INVALID_CHARACTER );  
  133.   
  134.         if(*(src+i) > 127 || base64_dec_map[*(src+i)] == 127 )  
  135.             return( XYSSL_ERR_BASE64_INVALID_CHARACTER );  
  136.   
  137.         if( base64_dec_map[*(src+i)] < 64 && j != 0 )  
  138.             return( XYSSL_ERR_BASE64_INVALID_CHARACTER );  
  139.   
  140.         n++;  
  141.     }  
  142.   
  143.     if( n == 0 )  
  144.         return( 0 );  
  145.   
  146.     n = ((n * 6) + 7) >> 3;  
  147.   
  148.     if( *dlen < n )  
  149.     {  
  150.         *dlen = n;  
  151.         return( XYSSL_ERR_BASE64_BUFFER_TOO_SMALL );  
  152.     }  
  153.   
  154.     for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ )  
  155.     {  
  156.         if( *src == '/r' || *src == '/n' )  
  157.         continue;  
  158.   
  159.         j -= ( base64_dec_map[*src] == 64 );  
  160.         x = (x << 6) | ( base64_dec_map[*src] & 0x3F );  
  161.   
  162.         if( ++n == 4 )  
  163.         {  
  164.             n = 0;  
  165.             if( j > 0 ) *p++ = (unsigned char)( x >> 16 );  
  166.             if( j > 1 ) *p++ = (unsigned char)( x >> 8 );  
  167.             if( j > 2 ) *p++ = (unsigned char)( x );  
  168.         }  
  169.     }  
  170.   
  171.     *dlen =static_cast<int>(p - dst);  
  172.   
  173.     return( 0 );  
  174. }  
  175.   
  176.   
  177. BOOL CBase64::Encrypt(const unsigned char *pSrc,int iSlen,unsigned char *pDst,int *iDlen,CString &strErrorInfo)  
  178. {  
  179.     strErrorInfo=_T("");  
  180.     int iRet=base64_encode(pSrc,iSlen,pDst,iDlen);  
  181.     if(iRet==XYSSL_ERR_BASE64_BUFFER_TOO_SMALL)  
  182.         strErrorInfo=_T("分配的缓冲区太小!");  
  183.     else if(iRet==XYSSL_ERR_BASE64_INVALID_CHARACTER)  
  184.         strErrorInfo=_T("无效数据!");  
  185.     return iRet==0;   
  186. }  
  187. BOOL CBase64::Decrypt(const unsigned char *pSrc,int iSlen,unsigned char *pDst,int *iDlen,CString &strErrorInfo)  
  188. {  
  189.     strErrorInfo=_T("");  
  190.     int iRet=base64_decode(pSrc,iSlen,pDst,iDlen);  
  191.     if(iRet==XYSSL_ERR_BASE64_BUFFER_TOO_SMALL)  
  192.         strErrorInfo=_T("分配的缓冲区太小!");  
  193.     else if(iRet==XYSSL_ERR_BASE64_INVALID_CHARACTER)  
  194.         strErrorInfo=_T("无效数据!");  
  195.     return iRet==0;   

0 0
原创粉丝点击