master
Evan Chen 2021-11-17 09:44:15 +08:00
commit 661d831133
4 changed files with 53 additions and 0 deletions

0
README.md Normal file
View File

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module kumoly.io/lib/xorencrypt
go 1.17

25
xorencrypt.go Normal file
View File

@ -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
}

25
xorencrypt_test.go Normal file
View File

@ -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)
}