Golang、python中的一個異或密碼編譯演算法,用來加密字串。

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

在Go語言中,有內建的對稱或者非對稱式加密函數,但是有點重量級,用起來也有點麻煩。

一般的遊戲設計中,肯定不用Go內建的那些加密庫,因為處理速度有點慢,伺服器跟不上速度,用戶端也跟不上速度。

在delphi中和易語言中我經常用這個演算法加密,演算法是網上抄的:

XorKey可以自己自訂修改。

delphi代碼:

const   XorKey: array[0..7] of Byte = ($B2, $09, $BB, $55, $93, $6D, $44, $47); //字串加密用function Enc(Str: string): string; //字元加密函數  這是用的一個異或加密var   i, j: Integer;begin   Result := '';   j := 0;   for i := 1 to Length(Str) do   begin      Result := Result + IntToHex(Byte(Str[i]) xor XorKey[j], 2);      j := (j + 1) mod 8;   end;end;             function Dec(Str: string): string; //字元解密函數var   i, j: Integer;begin   Result := '';   j := 0;   for i := 1 to Length(Str) div 2 do   begin      Result := Result + Char(StrToInt('$' + Copy(Str, i * 2 - 1, 2)) xor XorKey[j]);      j := (j + 1) mod 8;   end;end;

 

用Go語言改寫後,是這樣的。可以自己最佳化下處理。

var XorKey []byte = []byte{0xB2, 0x09, 0xBB, 0x55, 0x93, 0x6D, 0x44, 0x47}type Xor struct {}type m interface {   enc(src string) string   dec(src string) string}func (a *Xor) enc(src string) string {   var result string   j := 0   s := ""   bt := []rune(src)   for i := 0; i < len(bt); i++ {      s = strconv.FormatInt(int64(byte(bt[i])^XorKey[j]), 16)      if len(s) == 1 {         s = "0" + s      }      result = result + (s)      j = (j + 1) % 8   }   return result}func (a *Xor) dec(src string) string {   var result string   var s int64   j := 0   bt := []rune(src)   fmt.Println(bt)   for i := 0; i < len(src)/2; i++ {      s, _ = strconv.ParseInt(string(bt[i*2:i*2+2]), 16, 0)      result = result + string(byte(s)^XorKey[j])      j = (j + 1) % 8   }   return result}func main() {   xor := Xor{}   fmt.Println(xor.enc("123fsgdg0fd"))   fmt.Println(xor.dec("833b8833e00a2020826fdf"))}

 

python中,可以這樣來寫。

class Xor:    XorKey=[0xB2, 0x09, 0xBB, 0x55, 0x93, 0x6D, 0x44, 0x47]    def __init__(self):        pass    @classmethod    def enc(self,src):        j,result=0,""        bt=bytes(src,'ascii')        h=len(bt)        for i in range(h):           result=result+hex(bt[i]^(self.XorKey[j]))[2:]           j=(j+1)%8        return result    @classmethod    def dec(self,src):        j,result,h=0,"",0        h=len(src)        for i in range(0,h,2):           result=result + chr (int( src[i:i+2],16)^self.XorKey[j])           j=(j+1)%8        return resulta=Xor()print(a.enc("123fsgdg0fd"))print(a.dec("833b8833e00a2020826fdf"))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.