53 lines
1.2 KiB
Go
53 lines
1.2 KiB
Go
package protocol
|
|
|
|
import (
|
|
"bytes"
|
|
"git.viry.cc/gomod/util"
|
|
"testing"
|
|
)
|
|
|
|
func TestEncryptorXor(t *testing.T) {
|
|
var ori, data, key, ans []byte
|
|
|
|
for i := 1; i < 1024; i++ {
|
|
ori = util.RandomKey(i).Bytes()
|
|
data = make([]byte, len(ori))
|
|
copy(data, ori)
|
|
for j := 1; j < 128; j++ {
|
|
key = util.RandomKey(j).Bytes()
|
|
// build ans
|
|
ans = make([]byte, len(ori))
|
|
copy(ans, ori)
|
|
for k := range ans {
|
|
ans[k] ^= key[k%j]
|
|
}
|
|
// check
|
|
SetEncryptorXorKey(key)
|
|
pkg := newPackage(0, 0, 0, data)
|
|
pkg.xorEncrypt()
|
|
if !bytes.Equal(pkg.body, ans) {
|
|
t.Errorf("expected [%0#2v] got [%0#2v]\n", ans, data)
|
|
}
|
|
pkg.xorDecrypt()
|
|
if uint32(len(pkg.body)) != pkg.bodySize || pkg.bodySize != uint32(len(ori)) {
|
|
t.Errorf("expected [%d] got [%d, %d]\n", uint32(len(ori)), pkg.bodySize, uint32(len(pkg.body)))
|
|
}
|
|
if !bytes.Equal(pkg.body, ori) {
|
|
t.Errorf("expected [%0#2v] got [%0#2v]\n", ori, data)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func BenchmarkEncryptorXorEncode(b *testing.B) {
|
|
data := util.RandomKey(256 * 1024 * 1024).Bytes()
|
|
key := util.RandomKey(16).Bytes()
|
|
pkg := newPackage(0, 0, 0, data)
|
|
SetEncryptorXorKey(key)
|
|
b.ResetTimer()
|
|
for i := 0; i < b.N; i++ {
|
|
pkg.xorEncrypt()
|
|
pkg.xorDecrypt()
|
|
}
|
|
}
|