提醒:本页面将不再更新、维护或者支持,文章、评论所叙述内容存在时效性,涉及技术细节或者软件使用方面不保证能够完全有效可操作,请谨慎参考!

可能很多人听说过 Base64 编码,很少有人听说过Base24编码,Base24编码主要应用在序列号生成上,其实基本的算法思想都是一样的,只是编码的模式有点变化。
Base64 所对应的编码表是
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
共计64位。
而Base24所对应的编码表是
BCDFGHJKMPQRTVWXY2346789
共计24位,这里主要去掉了一些对于序列号来说不容易识别和容易混淆的字符。

具体算法网上都有介绍我就不再赘述,下面直接谈怎么编码实现吧:-)

对于 Base64 算法的C语言实现,大家可以参考Bob Trower的经典开源项目b64.c,网址是 http://base64.sourceforge.net/

在这里我要谈的是如何用ASP进行 Base64 编码,网上搜索出的一大堆算法不是太复杂就是运行不准确,其实ASP的Base64编码可以很简单,当然要用到服务器的一个COM组件XmlDom,具体思路是这样的,首先创建个临时的节点tmp,然后给结点tmp,设置datatype = "bin.base64",这样就可以进行相应的编解码了,对于文本字符串的编解码还要用ADODB.Stream进行一次编码转换。

Base64的ASP实现:

Class CBase64
  Private objXmlDom
  Private objXmlNode
  
  ' GetObjectParam() 这个函数实现参考了开源项目PJBlog
  Private Function GetObjectParam()
   On Error Resume Next
   Dim Temp
   GetObjectParam = "Microsoft.XMLDOM"
   Err = 0
   Dim TmpObj
   Set TmpObj = Server.CreateObject(GetObjectParam)
   Temp = Err.Number
   If Temp = 1 Or Temp = -2147221005 Then
       GetObjectParam = "Msxml2.DOMDocument.5.0"
    End If
    Err.Clear
    Set TmpObj = Nothing
   Err = 0
  End Function
  
  Private Sub Class_Initialize()
      Set objXmlDom = Server.CreateObject(GetObjectParam())
  End Sub
  
  Private Sub Class_Terminate()
      Set objXmlDom = Nothing
  End Sub

  Public Function encode(AnsiCode)
    encode = ""
    Set objXmlNode = objXmlDom.createElement("tmp")
    objXmlNode.datatype = "bin.base64"
    objXmlNode.nodeTypedvalue = AnsiCode
    encode = objXmlNode.Text
    Set objXmlNode = Nothing
  End Function
  
  Public Function decode(base64Code)
    On Error Resume Next
    decode = ""
    Set objXmlNode = objXmlDom.createElement("tmp")
    objXmlNode.datatype = "bin.base64"
    objXmlNode.Text = base64Code
    decode = objXmlNode.nodeTypedvalue
    Set objXmlNode = Nothing
    If Err Then
        Err.Clear
    End If
  End Function
  
  ' 以下函数编码字符串
  Public Function encodeText(ByVal str)
    On Error Resume Next
    Dim ado, r: r = ""
    If str <> "" Then
    Set ado = Server.CreateObject("ADODB.Stream")
        With ado
            .Charset = "gb2312"
            .Type = 2
            If .State = 0 Then .Open
            .WriteText str
            .Position = 0
            .Type = 1
            r = encode(.Read(-1))
            .Close
        End With
    Set ado = Nothing
    End If
    If Err Then Err.Clear: r = ""
    encodeText = r
  End Function
  
  ' 以下函数解码字符串
  Public Function decodeText(ByVal str)
    On Error Resume Next
    Dim ado, r: r = ""
    If str <> "" Then
    Set ado = Server.CreateObject("ADODB.Stream")
        With ado
            .Charset = "gb2312"
            .Type = 1
            If .State = 0 Then .Open
            .Write (decode(str))
            .Position = 0
            .Type = 2
            r = .ReadText(-1)
            .Close
        End With
    Set ado = Nothing
    End If
    If Err Then Err.Clear: r = ""
    decodeText = r
  End Function
End Class

写到这里想起以前项目里改写过一段Base64和16进制互转的代码,在这里与大家分享下。

' Base64转16进制
Function B64ToHex(ByVal strContent)
  Dim i,strReturned, b64pad, _
       b64map, chTemp, intLocate, k , slop
  strReturned = "" : k = 0
  b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZ" &_
              "abcdefghijklmnopqrstuvwxyz0123456789+/"
  b64pad="="
  For i=0 To Len(strContent)-1
     chTemp = Mid(strContent, i+1, 1)
     If chTemp = b64pad Then Exit For
     intLocate = InStr(1, b64map, chTemp, 0)-1
     If intLocate > -1 Then
         Select Case K
           Case 0
           strReturned = strReturned &_
                             Int2Char(Int(intLocate / 4))
           slop = intLocate And 3 :  k = 1
           Case 1
           strReturned = strReturned &_
                              Int2Char( (slop * 4) Or (Int(intLocate / 16)) )
          slop = intLocate And &h0f :  k = 2
          Case 2
          strReturned = strReturned &_
                             Int2Char(slop) & Int2Char(Int(intLocate / 4))
          slop = intLocate And 3  : k=3
          Case Else
          strReturned = strReturned &_
                             Int2Char( (slop * 4) Or (Int(intLocate / 16)) ) &_
                             Int2Char(intLocate And &h0f)
          k = 0
        End Select
     End If
  Next
  If k=1 Then strReturned = strReturned & Int2Char(slop * 4)
  B64ToHex = strReturned
End Function

' 16进制转Base64
Function HexToB64(ByVal strContent)
  Dim i, c, strReturned, b64map, b64pad, intLen
  b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZ" &_
             "abcdefghijklmnopqrstuvwxyz0123456789+/"
  b64pad="="
  intLen = Len(strContent)
  For i=0 To intLen-3 Step 3
      c=Clng("&h" & Mid(strContent,i+1,3))
      strReturned = strReturned &_
                         Mid(b64map, Int(c / 64 +1), 1) &_
                         Mid(b64map, (c And 63)+1, 1)
  Next

  If i+1=intLen Then
     c =Clng("&h" & Mid(strContent,i+1,1))
     strReturned = strReturned & Mid(b64map, c * 4 + 1, 1)
  ElseIf i+2=intLen Then
     c =Clng("&h" & Mid(strContent,i+1,2))
     strReturned = strReturned & Mid(b64map, Int(c / 4) + 1, 1) &_
                        Mid(b64map, (c And 3)*16+1, 1)		
  End If

  While (Len(strReturned) And 3) >0
      strReturned = strReturned & b64pad
  Wend
  HexToB64 = strReturned
End Function

有关Base24的代码实现网上也有很多,这里给出两种不同程序语言的实现供参考。

Base24的C语言实现

static const char sel[] = {
	'B','C','D','F','G',
	'H','J','K','M','P',
	'Q','R','T','V','W',
	'X','Y','2','3','4',
	'6','7','8','9', '\0'};

char *b24e(char *buf, unsigned char *byst, size_t sizeOfBytes)
{
	int i = 0;
	unsigned char *p = byst;
	while ((size_t)(i = (p-byst)) < sizeOfBytes) {
		buf[2*i] = sel[((*p) >> 4)];
		buf[(2*i)+1] = sel[23 - ((*p) & 0x0f)];
		p++;
	}
	buf[(2*i)+1] = '\0';
	return buf;
}

unsigned char *b24d(unsigned char *buf, char *str, size_t countOfChars)
{
	size_t i;
	char *p = str;
	char *loc[2];
	unsigned char n[2];
	if (countOfChars % 2)
		return NULL;
	for (i = 0; i < (countOfChars>>1); i++) {
		
		loc[0] = strchr( sel, str[2*i] );
		loc[1] = strchr( sel, str[ ( 2*i ) + 1 ] );
		if (loc[0] == NULL || loc[1] == NULL)
			return NULL;
		n[0] = (unsigned char)( loc[0] - sel );
		n[1] = 23 - (unsigned char)( loc[1] - sel );
		buf[i] = (unsigned char)((n[0] << 4) | n[1]);
	}
	return buf;
}

后来由于项目需要,我特地改写了C#版。

public static class Base24
{
  private static string sel = "BCDFGHJKMPQRTVWXY2346789";
        
  public static string Encode(string Text)
  {
    int i = 0;
    int Pos = 0;
    char []Buf = new char[Text.Length<<1];

    while ((i = Pos) < Text.Length)
    {
        Buf[i<<1] = sel[(Text[Pos]) >> 4];
        Buf[(i<<1) + 1] = sel[23 - (Text[Pos] & 0x0F)];
        Pos++;
     }

        return new string(Buf);
    }

    public static string Decode(string Text)
    {
        if (Text.Length % 2 != 0)
            return null;

        int [] NPos = new int[2];
        char[] N = new char[2];
        char[] Buf = new char[Text.Length >> 1];

        for (int i = 0; i < (Text.Length >> 1); i++)
        {
            NPos[0] = sel.IndexOf(Text[ i<<1 ]);
            NPos[1] = 23 - sel.IndexOf(Text[(i<<1) + 1]);
            if (NPos[0] < 0 || NPos[1] < 0) {
                return null;
            }

            Buf[i] = ((char)((NPos[0] << 4) | NPos[1]));
        }
            return new string(Buf);
    }
}
  1. Base64 : Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一。 [更多]