Instantly share code, notes, and snippets.

# inkedawn/encrypt.go Created Dec 29, 2018

Packet Encrypt Algorithm of taomee game Seer2
 package encrypt const ( Key = "taomee_seer2_k_~#" ) // 异或加解密 func xorCalc(result []byte, raw []byte, key []byte) { if len(result) != len(raw) { panic(len(result)) } for i, oneByte := range raw { result[i] = oneByte ^ key[i%len(key)] } return } func Encrypt(rawData []byte) (encrypted []byte, success bool) { if len(rawData) < 1 { return nil, false } encrypted = make([]byte, len(rawData)+1) // 第一次处理 xorCalc(encrypted[:len(rawData)], rawData, []byte((Key))) // 第二次处理 encrypted[len(encrypted)-1] = 0 //最后一位置0 for i := len(encrypted) - 1; i > 0; i-- { encrypted[i] |= encrypted[i-1] >> 3 encrypted[i-1] <<= 5 } encrypted[0] |= 3 return encrypted, true } func Decrypt(encrypted []byte) (decrypted []byte, success bool) { if len(encrypted) < 1 { return nil, false } decrypted = make([]byte, len(encrypted)-1) // 第一次处理 for i := 0; i < len(decrypted); i++ { decrypted[i] = (encrypted[i+1] << 3) | (encrypted[i] & 224 >> 5) } // 第二次处理 xorCalc(decrypted[:], decrypted, []byte((Key))) return decrypted, true }
 package encrypt import ( "bytes" "testing" ) var testCaseData = [...][2][]byte{ { {0xde, 0x2, 0x1f, 0x3, 0x6d, 0x4, 0x0, 0x0, 0xe8, 0x2, 0x0, 0x0, 0xe9, 0x0, 0x0, 0x0}, {0x43, 0x75, 0x0C, 0xCE, 0x0D, 0x21, 0xEC, 0x6B, 0xAE, 0xF1, 0x4C, 0x4E, 0xC6, 0x76, 0xED, 0xCB, 0x0F}, }, { {0xde, 0x2, 0x1f, 0x3, 0x78, 0x4, 0x0, 0x0, 0xf3, 0x2, 0x0, 0x0, 0xe9, 0x0, 0x0, 0x0}, {0x43, 0x75, 0x0C, 0xCE, 0xAD, 0x23, 0xEC, 0x6B, 0xCE, 0xF2, 0x4C, 0x4E, 0xC6, 0x76, 0xED, 0xCB, 0x0F}, }, { {0xde, 0x2, 0x1f, 0x3, 0x61, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x27, 0xb8, 0xa9, 0x0, 0xe8, 0x1c, 0x6a, 0xe, 0x42, 0xe2, 0x0, 0x3a}, {0x43, 0x75, 0x0C, 0xCE, 0x8D, 0x20, 0xEC, 0x6B, 0xAE, 0xAC, 0x4C, 0x4E, 0x06, 0x6F, 0xDA, 0xDE, 0x6F, 0x19, 0x6D, 0x21, 0xEC, 0xE5, 0xB0, 0xAC, 0x0C}, }, } func Test_encrypt(t *testing.T) { for _, tCase := range testCaseData { rawData := tCase[0] expected := tCase[1] result, ok := Encrypt(rawData) if !ok { t.Errorf("function failed when testing case %v", rawData) t.Fail() continue } if !bytes.Equal(result, expected) { t.Errorf("Case not passed: %v\n", rawData) t.Errorf("It's expected to be: %v\n", expected) t.Fail() } } } func Test_decrypt(t *testing.T) { for _, tCase := range testCaseData { rawData := tCase[1] expected := tCase[0] result, ok := Decrypt(rawData) if !ok { t.Errorf("function failed when testing case %v", rawData) t.Fail() continue } if !bytes.Equal(result, expected) { t.Errorf("Case not passed: %v\n", rawData) t.Errorf("It's expected to be: %v\n", expected) t.Fail() } } }