码迷,mamicode.com
首页 > 其他好文 > 详细

关于BASE 24 ,BASE 64原理以及实现程序

时间:2019-12-11 12:41:47      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:The   ++   erro   nat   private   cat   bytes   style   syntax   

关于BASE 24 ,BASE 64原理以及实现程序

来源 https://wangye.org/blog/archives/5/

 

可能很多人听说过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);
    }
}

 

=============== End
 

 

关于BASE 24 ,BASE 64原理以及实现程序

标签:The   ++   erro   nat   private   cat   bytes   style   syntax   

原文地址:https://www.cnblogs.com/lsgxeva/p/12021597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!