C#實現Base64編碼與解碼

l_serein發表於2012-11-13

一、編碼規則
      Base64編碼的思想是是採用64個基本的ASCII碼字元對資料進行重新編碼。它將需要編碼的資料拆分成位元組陣列。以3個位元組為一組。按順序排列24 位資料,再把這24位資料分成4組,即每組6位。再在每組的的最高位前補兩個0湊足一個位元組。這樣就把一個3位元組為一組的資料重新編碼成了4個位元組。當所要編碼的資料的位元組數不是3的整倍數,也就是說在分組時最後一組不夠3個位元組。這時在最後一組填充1到2個0位元組。並在最後編碼完成後在結尾新增1到2個 “=”。

例:將對ABC進行BASE64編碼:


1、首先取ABC對應的ASCII碼值。A(65)B(66)C(67);
2、再取二進位制值A(01000001)B(01000010)C(01000011);
 3、然後把這三個位元組的二進位制碼接起來(010000010100001001000011);
4、 再以6位為單位分成4個資料塊,並在最高位填充兩個0後形成4個位元組的編碼後的值,(00010000)(00010100)(00001001)(00000011),其中藍色部分為真實資料;
 5、再把這四個位元組資料轉化成10進位制數得(16)(20)(9)(3);
 6、最後根據BASE64給出的64個基本字元表,查出對應的ASCII碼字元(Q)(U)(J)(D),這裡的值實際就是資料在字元表中的索引。

注:BASE64字元表:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

二、解碼規則
      解碼過程就是把4個位元組再還原成3個位元組再根據不同的資料形式把位元組陣列重新整理成資料。

三、C#中的實現

編碼類:

/// <summary>
    
/// Base64編碼類。
    
/// 將byte[]型別轉換成Base64編碼的string型別。
    
/// </summary>
    public class Base64Encoder
    {
        
byte[] source;
        
int length, length2;
        
int blockCount;
        
int paddingCount;
        
public static Base64Encoder Encoder = new Base64Encoder();

        
public Base64Encoder()
        {
        }

        
private void init(byte[] input)
        {
            source 
= input;
            length 
= input.Length;
            
if ((length % 3== 0)
            {
                paddingCount 
= 0;
                blockCount 
= length / 3;
            }
            
else
            {
                paddingCount 
= 3 - (length % 3);
                blockCount 
= (length + paddingCount) / 3;
            }
            length2 
= length + paddingCount;
        }

        
public string GetEncoded(byte[] input)
        {
            
//初始化
            init(input);

            
byte[] source2;
            source2 
= new byte[length2];

            
for (int x = 0; x < length2; x++)
            {
                
if (x < length)
                {
                    source2[x] 
= source[x];
                }
                
else
                {
                    source2[x] 
= 0;
                }
            }

            
byte b1, b2, b3;
            
byte temp, temp1, temp2, temp3, temp4;
            
byte[] buffer = new byte[blockCount * 4];
            
char[] result = new char[blockCount * 4];
            
for (int x = 0; x < blockCount; x++)
            {
                b1 
= source2[x * 3];
                b2 
= source2[x * 3 + 1];
                b3 
= source2[x * 3 + 2];

                temp1 
= (byte)((b1 & 252>> 2);

                temp 
= (byte)((b1 & 3<< 4);
                temp2 
= (byte)((b2 & 240>> 4);
                temp2 
+= temp;

                temp 
= (byte)((b2 & 15<< 2);
                temp3 
= (byte)((b3 & 192>> 6);
                temp3 
+= temp;

                temp4 
= (byte)(b3 & 63);

                buffer[x 
* 4= temp1;
                buffer[x 
* 4 + 1= temp2;
                buffer[x 
* 4 + 2= temp3;
                buffer[x 
* 4 + 3= temp4;

            }

            
for (int x = 0; x < blockCount * 4; x++)
            {
                result[x] 
= sixbit2char(buffer[x]);
            }


            
switch (paddingCount)
            {
                
case 0break;
                
case 1: result[blockCount * 4 - 1= '='break;
                
case 2: result[blockCount * 4 - 1= '=';
                    result[blockCount 
* 4 - 2= '=';
                    
break;
                
defaultbreak;
            }
            
return new string(result);
        }
        
private char sixbit2char(byte b)
        {
            
char[] lookupTable = new char[64]{
                  
'A','B','C','D','E','F','G','H','I','J','K','L','M',
                 
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                 
'a','b','c','d','e','f','g','h','i','j','k','l','m',
                 
'n','o','p','q','r','s','t','u','v','w','x','y','z',
                 
'0','1','2','3','4','5','6','7','8','9','+','/'};

            
if ((b >= 0&& (b <= 63))
            {
                
return lookupTable[(int)b];
            }
            
else
            {

                
return ' ';
            }
        }

    }


解碼類:

/// <summary>
    
/// Base64解碼類
    
/// 將Base64編碼的string型別轉換成byte[]型別
    
/// </summary>
    public class Base64Decoder
    {
        
char[] source;
        
int length, length2, length3;
        
int blockCount;
        
int paddingCount;
        
public static Base64Decoder Decoder = new Base64Decoder();

        
public Base64Decoder()
        {
        }

        
private void init(char[] input)
        {
            
int temp = 0;
            source 
= input;
            length 
= input.Length;

            
for (int x = 0; x < 2; x++)
            {
                
if (input[length - x - 1== '=')
                    temp
++;
            }
            paddingCount 
= temp;

            blockCount 
= length / 4;
            length2 
= blockCount * 3;
        }

        
public byte[] GetDecoded(string strInput)
        {
            
//初始化
            init(strInput.ToCharArray());

            
byte[] buffer = new byte[length];
            
byte[] buffer2 = new byte[length2];

            
for (int x = 0; x < length; x++)
            {
                buffer[x] 
= char2sixbit(source[x]);
            }

            
byte b, b1, b2, b3;
            
byte temp1, temp2, temp3, temp4;

            
for (int x = 0; x < blockCount; x++)
            {
                temp1 
= buffer[x * 4];
                temp2 
= buffer[x * 4 + 1];
                temp3 
= buffer[x * 4 + 2];
                temp4 
= buffer[x * 4 + 3];

                b 
= (byte)(temp1 << 2);
                b1 
= (byte)((temp2 & 48>> 4);
                b1 
+= b;

                b 
= (byte)((temp2 & 15<< 4);
                b2 
= (byte)((temp3 & 60>> 2);
                b2 
+= b;

                b 
= (byte)((temp3 & 3<< 6);
                b3 
= temp4;
                b3 
+= b;

                buffer2[x 
* 3= b1;
                buffer2[x 
* 3 + 1= b2;
                buffer2[x 
* 3 + 2= b3;
            }

            length3 
= length2 - paddingCount;
            
byte[] result = new byte[length3];

            
for (int x = 0; x < length3; x++)
            {
                result[x] 
= buffer2[x];
            }

            
return result;
        }

        
private byte char2sixbit(char c)
        {
            
char[] lookupTable = new char[64]{  
                 
'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
                 
'O','P','Q','R','S','T','U','V','W','X','Y''Z',
                 
'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
                 
'o','p','q','r','s','t','u','v','w','x','y','z',
                 
'0','1','2','3','4','5','6','7','8','9','+','/'};
            
if (c == '=')
                
return 0;
            
else
            {
                
for (int x = 0; x < 64; x++)
                {
                    
if (lookupTable[x] == c)
                        
return (byte)x;
                }

                
return 0;
            }

        }
    }
    
//解碼類結束


提示:

上面的程式碼只是說明base64編碼的原理,以便用更多語言重寫。但.net裡面可以使用更簡單的方法:
編碼:
byte[] bytes=Encoding.Default.GetBytes("要轉換的字串");
Convert.ToBase64String(bytes);
解碼:
//"ztKwrsTj"是“我愛你”的base64編碼
byte[] outputb = Convert.FromBase64String("ztKwrsTj");
string orgStr= Encoding.Default.GetString(outputb);


完!

相關文章