Golang/Delphi实现的异或加密的方法
异或加密是一个比较简单的加密方法,之前写了一个小工具,近期服务端从Delphi改为Golang了,里面用到了一个异或加密的算法,这里分享下具体的实现:
Golang版本实现方法:
package xor
import (
"strconv"
)
// DefaultKey ...
const DefaultKey = "www.5bug.wang"
// Enc ...
func Enc(src, key string) (des string) {
if key == "" {
key = DefaultKey
}
keys := []byte(key)
j := 0
bt := []rune(src)
for i := 0; i < len(bt); i++ {
s := strconv.FormatInt(int64(byte(bt[i])^keys[j]), 16)
if len(s) == 1 {
s = "0" + s
}
des = des + (s)
j = (j + 1) % 8
}
return
}
// Dec ...
func Dec(src, key string) (des string) {
if key == "" {
key = DefaultKey
}
keys := []byte(key)
j := 0
bt := []rune(src)
for i := 0; i < len(src)/2; i++ {
l, _ := strconv.ParseInt(string(bt[i*2:i*2+2]), 16, 0)
des = des + string(byte(l)^keys[j])
j = (j + 1) % 8
}
return
}delphi版本实现方法:
unit uXor;
interface
uses System.SysUtils;
function XorEnc(AStr: string; AKey: string = ''): string;
function XorDec(AStr: string; AKey: string = ''): string;
implementation
const
DefaultKey = 'www.5bug.wang';
function XorEnc(AStr: string; AKey: string): string;
var
i, j: Integer;
LBytes: TBytes;
begin
if AKey = '' then
AKey := DefaultKey;
LBytes := BytesOf(AKey);
Result := '';
j := 0;
for i := 1 to Length(AStr) do
begin
Result := Result + IntToHex(Byte(AStr[i]) xor LBytes[j], 2);
j := (j + 1) mod 8;
end;
end;
function XorDec(AStr: string; AKey: string): string;
var
i, j: Integer;
LBytes: TBytes;
begin
if AKey = '' then
AKey := DefaultKey;
LBytes := BytesOf(AKey);
Result := '';
j := 0;
for i := 1 to Length(AStr) div 2 do
begin
Result := Result + Char(StrToInt('$' + Copy(AStr, i * 2 - 1, 2)) xor LBytes[j]);
j := (j + 1) mod 8;
end;
end;
end.