這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
在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"))