commit 661d8311330ad372c666efe7c7da9aae42834a76 Author: Evan Chen Date: Wed Nov 17 09:44:15 2021 +0800 init diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..1e378cd --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module kumoly.io/lib/xorencrypt + +go 1.17 diff --git a/xorencrypt.go b/xorencrypt.go new file mode 100644 index 0000000..a2fed56 --- /dev/null +++ b/xorencrypt.go @@ -0,0 +1,25 @@ +package xorencrypt + +import "encoding/base64" + +func Decrypt(msg, key string) (string, error) { + deb64, err := base64.StdEncoding.DecodeString(msg) + if err != nil { + return "", err + } + dec := xor(deb64, []byte(key)) + return string(dec), nil +} + +func Encrypt(msg, key string) string { + enc := xor([]byte(msg), []byte(key)) + return base64.StdEncoding.EncodeToString(enc) +} + +func xor(msg, key []byte) []byte { + ret := make([]byte, len(msg)) + for i := 0; i < len(msg); i++ { + ret[i] = msg[i] ^ key[i%len(key)] + } + return ret +} diff --git a/xorencrypt_test.go b/xorencrypt_test.go new file mode 100644 index 0000000..49b6ae1 --- /dev/null +++ b/xorencrypt_test.go @@ -0,0 +1,25 @@ +package xorencrypt + +import ( + "fmt" + "testing" +) + +func TestXOR(t *testing.T) { + msg := "test" + key := "key" + enc := xor([]byte(msg), []byte(key)) + dec := xor([]byte(enc), []byte(key)) + fmt.Printf("%s -> %d -> %s\n", msg, enc, dec) +} + +func TestEncrypt(t *testing.T) { + msg := "test" + key := "key" + enc := Encrypt(msg, key) + dec, _ := Decrypt(enc, key) + fmt.Printf("%s -> %s -> %s\n", msg, enc, dec) + + decErr, _ := Decrypt(enc, "wrongKey") + fmt.Printf("%s -> %s -> %s\n", msg, enc, decErr) +}