Skip to content

Commit

Permalink
add xor encrypt and decrypt
Browse files Browse the repository at this point in the history
  • Loading branch information
james committed Mar 13, 2024
1 parent 9ccb117 commit 07b32d8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
31 changes: 31 additions & 0 deletions lib/gutil/gutil.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gutil

import (
"encoding/base64"
"fmt"
"io/ioutil"
"math/rand"
Expand All @@ -11,6 +12,7 @@ import (
"runtime/debug"
"strings"
"time"
"unsafe"

"github.com/bwmarrin/snowflake"
uuid "github.com/satori/go.uuid"
Expand Down Expand Up @@ -117,6 +119,35 @@ func CallFunc(fn interface{}, args []interface{}) {
reflect.ValueOf(fn).Call(as)
}

/////////////////////////////////////////////////////////////////
// encrypt funcs

func XOR(bPlain []byte, bKey []byte) []byte {
bCipher := make([]byte, len(bPlain))
keyLength := len(bKey)
for i, k := range bPlain {
bCipher[i] = k ^ bKey[i%keyLength]
}
return bCipher
}

func EncryptXOR(sPlain string, bKey []byte) string {
pPlain := *(*reflect.StringHeader)(unsafe.Pointer(&sPlain))
bPlain := *(*[]byte)(unsafe.Pointer(&pPlain))
bCipher := XOR(bPlain, bKey)
sCipher := base64.StdEncoding.EncodeToString(bCipher)
return sCipher
}

func DecryptXOR(sEncypted string, bKey []byte) string {
bEncypted, err := base64.StdEncoding.DecodeString(sEncypted)
if err != nil {
panic("DecryptXOR base64 decode error")
}
bDecypted := XOR(bEncypted, bKey)
return string(bDecypted)
}

/////////////////////////////////////////////////////////////////
// util funcs

Expand Down
10 changes: 10 additions & 0 deletions lib/gutil/gutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ func TestUtil(t *testing.T) {
Dump("SFID", SFID())
}

func TestXOR(t *testing.T) {
key := []byte("KEY")
encrypt := EncryptXOR("testbyjames1中国", key)
decrypt := DecryptXOR(encrypt, key)
Dump("XOR encrypt", encrypt)
Dump("XOR decrypt", decrypt)
decrypt1 := DecryptXOR("KjY4Ly04Ii1oeazB9KPp/w==", key)
Dump("XOR decrypt1", decrypt1)
}

func TestThrow(t *testing.T) {
defer Catch()
Throw("exception:1")
Expand Down

0 comments on commit 07b32d8

Please sign in to comment.