1^0=1 0^0=0 1^1=0 23^32=55 55^32=23 23對32進行異或兩次運算結果爲23
設key=[]byte{1,2,3,4,5,6},src=[]byte{11,22,33,44,55,66,77,88,99}
將src與key左對齊進行異或位運算數組
for i:=0;i<len(src);i++{ src[i]^=key[i%len(key)] }
得到的src便是加密後的[]byte數組加密
將加密後的src與key左對齊進行異或位運算code
for i:=0;i<len(src);i++{ src[i]^=key[i%len(key)] }
得到的src便是解密後的[]byte數組string
func main() { key := "dGhpcyBpcyBhIGV4YW1wbGVjenh2enh2emZhc2ZhZmE" str:="abcdefghijklmnopq" strBase64:=base64.StdEncoding.EncodeToString([]byte(str)) fmt.Println("加密前:",strBase64) // 1.對strBase64加密 enCodeStrBase64:=XorEncode(strBase64,key) fmt.Println("加密後:",enCodeStrBase64) // 2,對enCodeStrBase64解密 deCodeStrBase64:=XorDecode(enCodeStrBase64,key) fmt.Println("解密:",deCodeStrBase64) } func xor(src []byte, key []byte) []byte { for i := 0; i < len(src); i++ { src[i] ^= key[i%len(key)] } return src } func XorDecode(src, key string) string { srcByte, _ := base64.StdEncoding.DecodeString(src) keyByte, _ := base64.StdEncoding.DecodeString(key) srcByte = xor(srcByte, keyByte) return base64.StdEncoding.EncodeToString(srcByte) } func XorEncode(src,key string)string{ return XorDecode(src,key) }
輸出結果:base64
加密前: YWJjZGVmZ2hpamtsbW5vcHE= 加密後: FQoKF0UPFEgISg4UDAMfHBQ= 解密: YWJjZGVmZ2hpamtsbW5vcHE=