zoukankan      html  css  js  c++  java
  • Base64加密解密原理以及代码实现(VC++)

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

    转自:http://blog.csdn.net/jacky_dai/article/details/4698461

        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. * /param dst destination buffer 
    17. * /param dlen size of the buffer 
    18. * /param src source buffer 
    19. * /param slen amount of data to be encoded 
    20. * /return 0 if successful, or XYSSL_ERR_BASE64_BUFFER_TOO_SMALL. 
    21. * *dlen is always updated to reflect the amount 
    22. * of data that has (or would have) been written. 
    23. * /note Call this function with *dlen = 0 to obtain the 
    24. * required buffer size in *dlen 
    25. */  
    26. int base64_encode(const unsigned char *src, int slen,unsigned char *dst, int *dlen);  
    27.   
    28. /** 
    29. * /brief Decode a base64-formatted buffer 
    30. * /param dst destination buffer 
    31. * /param dlen size of the buffer 
    32. * /param src source buffer 
    33. * /param slen amount of data to be decoded 
    34. * /return 0 if successful, XYSSL_ERR_BASE64_BUFFER_TOO_SMALL, or 
    35. * XYSSL_ERR_BASE64_INVALID_DATA if the input data is not 
    36. * correct. *dlen is always updated to reflect the amount 
    37. * of data that has (or would have) been written. 
    38. * /note Call this function with *dlen = 0 to obtain the 
    39. * required buffer size in *dlen 
    40. */  
    41. int base64_decode(const unsigned char *src, int slen,unsigned char *dst, int *dlen);  
    42.   
    43. /** 
    44. * /brief Checkup routine 
    45. * /return 0 if successful, or 1 if the test failed 
    46. */  
    47. int base64_self_test( int verbose );  
    48.   
    49. #ifdef __cplusplus  
    50. }  
    51. #endif  
    52.   
    53. class CBase64    
    54. {  
    55. public:  
    56.     CBase64();  
    57.     virtual ~CBase64();  
    58.     static BOOL Encrypt(const unsigned char *pSrc,int iSlen,unsigned char *pDst,int *iDlen,CString &strErrorInfo);  
    59.     static BOOL Decrypt(const unsigned char *pSrc,int iSlen,unsigned char *pDst,int *iDlen,CString &strErrorInfo);  
    60. private:  
    61.   
    62. };  
    63.   
    64. #endif /* base64.h */  
    [cpp] view plaincopy
     
    1. //source file: base64.cpp  
    2.   
    3. /* 
    4. * RFC 1521 base64 encoding/decoding 
    5. * Copyright (C) 2006-2007 Christophe Devine 
    6. * This library is free software; you can redistribute it and/or 
    7. * modify it under the terms of the GNU Lesser General Public 
    8. * License, version 2.1 as published by the Free Software Foundation. 
    9. * This library is distributed in the hope that it will be useful, 
    10. * but WITHOUT ANY WARRANTY; without even the implied warranty of 
    11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
    12. * Lesser General Public License for more details. 
    13. * You should have received a copy of the GNU Lesser General Public 
    14. * License along with this library; if not, write to the Free Software 
    15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
    16. * MA 02110-1301 USA 
    17. */  
    18. #include "stdafx.h"  
    19. #include "base64.h"  
    20.   
    21. static const unsigned char base64_enc_map[64] =  
    22. {  
    23. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',  
    24. 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',  
    25. 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',  
    26. 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',  
    27. 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',  
    28. 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',  
    29. '8', '9', '+', '/'  
    30. };  
    31.   
    32. static const unsigned char base64_dec_map[128] =  
    33. {  
    34. 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,  
    35. 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,  
    36. 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,  
    37. 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,  
    38. 127, 127, 127, 62, 127, 127, 127, 63, 52, 53,  
    39. 54, 55, 56, 57, 58, 59, 60, 61, 127, 127,  
    40. 127, 64, 127, 127, 127, 0, 1, 2, 3, 4,  
    41. 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,  
    42. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,  
    43. 25, 127, 127, 127, 127, 127, 127, 26, 27, 28,  
    44. 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,  
    45. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,  
    46. 49, 50, 51, 127, 127, 127, 127, 127  
    47. };  
    48.   
    49. /* 
    50. * Encode a buffer into base64 format 
    51. */  
    52. int base64_encode(const unsigned char *src, int slen,unsigned char *dst, int *dlen)  
    53. {  
    54.     int i, n;  
    55.     int C1, C2, C3;  
    56.     unsigned char *p;  
    57.   
    58.     if( slen == 0 )  
    59.     return( 0 );  
    60.   
    61.     n = (slen << 3) / 6;  
    62.   
    63.     switch( (slen << 3) - (n * 6) )  
    64.     {  
    65.     case 2: n += 3; break;  
    66.     case 4: n += 2; break;  
    67.     default: break;  
    68.     }  
    69.   
    70.     if( *dlen < n + 1 )  
    71.     {  
    72.         *dlen = n + 1;  
    73.         return( XYSSL_ERR_BASE64_BUFFER_TOO_SMALL );  
    74.     }  
    75.   
    76.     n = (slen / 3) * 3;  
    77.   
    78.     for( i = 0, p = dst; i < n; i += 3 )  
    79.     {  
    80.         C1 = *src++;  
    81.         C2 = *src++;  
    82.         C3 = *src++;  
    83.   
    84.         *p++ = base64_enc_map[(C1 >> 2) & 0x3F];  
    85.         *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];  
    86.         *p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F];  
    87.         *p++ = base64_enc_map[C3 & 0x3F];  
    88.     }  
    89.   
    90.     if( i < slen )  
    91.     {  
    92.         C1 = *src++;  
    93.         C2 = ((i + 1) < slen) ? *src++ : 0;  
    94.   
    95.         *p++ = base64_enc_map[(C1 >> 2) & 0x3F];  
    96.         *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];  
    97.   
    98.         if( (i + 1) < slen )  
    99.         *p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F];  
    100.         else *p++ = '=';  
    101.   
    102.         *p++ = '=';  
    103.     }  
    104.     *dlen =static_cast<int>(p - dst);  
    105.     *p = 0;  
    106.     return( 0 );  
    107. }  
    108.   
    109. /* 
    110. * Decode a base64-formatted buffer 
    111. */  
    112. int base64_decode(const unsigned char *src, int slen,unsigned char *dst, int *dlen)  
    113. {  
    114.     int i, j, n;  
    115.     unsigned long x;  
    116.     unsigned char *p;  
    117.   
    118.     for( i = j = n = 0; i < slen; i++ )  
    119.     {  
    120.         if( ( slen - i ) >= 2 &&  
    121.         *(src+i) == '/r' && *(src+i+1) == '/n' )  
    122.             continue;  
    123.   
    124.         if(*(src+i) == '/n' )  
    125.             continue;  
    126.   
    127.         if(*(src+i) == '=' && ++j > 2 )  
    128.             return( XYSSL_ERR_BASE64_INVALID_CHARACTER );  
    129.   
    130.         if(*(src+i) > 127 || base64_dec_map[*(src+i)] == 127 )  
    131.             return( XYSSL_ERR_BASE64_INVALID_CHARACTER );  
    132.   
    133.         if( base64_dec_map[*(src+i)] < 64 && j != 0 )  
    134.             return( XYSSL_ERR_BASE64_INVALID_CHARACTER );  
    135.   
    136.         n++;  
    137.     }  
    138.   
    139.     if( n == 0 )  
    140.         return( 0 );  
    141.   
    142.     n = ((n * 6) + 7) >> 3;  
    143.   
    144.     if( *dlen < n )  
    145.     {  
    146.         *dlen = n;  
    147.         return( XYSSL_ERR_BASE64_BUFFER_TOO_SMALL );  
    148.     }  
    149.   
    150.     for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ )  
    151.     {  
    152.         if( *src == '/r' || *src == '/n' )  
    153.         continue;  
    154.   
    155.         j -= ( base64_dec_map[*src] == 64 );  
    156.         x = (x << 6) | ( base64_dec_map[*src] & 0x3F );  
    157.   
    158.         if( ++n == 4 )  
    159.         {  
    160.             n = 0;  
    161.             if( j > 0 ) *p++ = (unsigned char)( x >> 16 );  
    162.             if( j > 1 ) *p++ = (unsigned char)( x >> 8 );  
    163.             if( j > 2 ) *p++ = (unsigned char)( x );  
    164.         }  
    165.     }  
    166.   
    167.     *dlen =static_cast<int>(p - dst);  
    168.   
    169.     return( 0 );  
    170. }  
    171.   
    172.   
    173. BOOL CBase64::Encrypt(const unsigned char *pSrc,int iSlen,unsigned char *pDst,int *iDlen,CString &strErrorInfo)  
    174. {  
    175.     strErrorInfo=_T("");  
    176.     int iRet=base64_encode(pSrc,iSlen,pDst,iDlen);  
    177.     if(iRet==XYSSL_ERR_BASE64_BUFFER_TOO_SMALL)  
    178.         strErrorInfo=_T("分配的缓冲区太小!");  
    179.     else if(iRet==XYSSL_ERR_BASE64_INVALID_CHARACTER)  
    180.         strErrorInfo=_T("无效数据!");  
    181.     return iRet==0;   
    182. }  
    183. BOOL CBase64::Decrypt(const unsigned char *pSrc,int iSlen,unsigned char *pDst,int *iDlen,CString &strErrorInfo)  
    184. {  
    185.     strErrorInfo=_T("");  
    186.     int iRet=base64_decode(pSrc,iSlen,pDst,iDlen);  
    187.     if(iRet==XYSSL_ERR_BASE64_BUFFER_TOO_SMALL)  
    188.         strErrorInfo=_T("分配的缓冲区太小!");  
    189.     else if(iRet==XYSSL_ERR_BASE64_INVALID_CHARACTER)  
    190.         strErrorInfo=_T("无效数据!");  
    191.     return iRet==0;   
    192. }  
    逃避不一定躲得过,面对不一定最难过
  • 相关阅读:
    Sprint2-3.0
    6/13 Sprint2 看板和燃尽图
    6/8/9/10/11 Sprint2 看板和燃尽图
    相互观看与评价
    复利计算器结对2.0
    汉堡包1.0
    复利计算5.0 结对
    《构建之法》第四章 二人合作 读后感
    复利计算器单元测试测试报告
    实验一、命令解释程序的编写实验
  • 原文地址:https://www.cnblogs.com/yangzhenlong/p/4797300.html
Copyright © 2011-2022 走看看