Skip to content

Commit 92c9ba0

Browse files
author
clowwindy
committed
optimize
1 parent af46629 commit 92c9ba0

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

shadowsocks/encrypt_salsa20.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import struct
55
import logging
66
import sys
7-
import encrypt
87

98
slow_xor = False
109
imported = False
@@ -32,8 +31,14 @@ def run_imports():
3231
def numpy_xor(a, b):
3332
if slow_xor:
3433
return py_xor_str(a, b)
35-
ab = numpy.frombuffer(a, dtype=numpy.byte)
36-
bb = numpy.frombuffer(b, dtype=numpy.byte)
34+
dtype = numpy.byte
35+
if len(a) % 4 == 0:
36+
dtype = numpy.uint32
37+
elif len(a) % 2 == 0:
38+
dtype = numpy.uint16
39+
40+
ab = numpy.frombuffer(a, dtype=dtype)
41+
bb = numpy.frombuffer(b, dtype=dtype)
3742
c = numpy.bitwise_xor(ab, bb)
3843
r = c.tostring()
3944
return r
@@ -80,8 +85,7 @@ def update(self, data):
8085

8186
if self._pos >= BLOCK_SIZE:
8287
self._next_stream()
83-
self._pos -= BLOCK_SIZE
84-
assert self._pos == 0
88+
self._pos = 0
8589
if not data:
8690
break
8791
return ''.join(results)
@@ -94,12 +98,12 @@ def test():
9498
rounds = 1 * 1024
9599
plain = urandom(BLOCK_SIZE * rounds)
96100
import M2Crypto.EVP
97-
cipher = M2Crypto.EVP.Cipher('aes_128_cfb', 'k' * 32, 'i' * 16, 1,
98-
key_as_bytes=0, d='md5', salt=None, i=1,
99-
padding=1)
100-
decipher = M2Crypto.EVP.Cipher('aes_128_cfb', 'k' * 32, 'i' * 16, 0,
101-
key_as_bytes=0, d='md5', salt=None, i=1,
102-
padding=1)
101+
# cipher = M2Crypto.EVP.Cipher('aes_128_cfb', 'k' * 32, 'i' * 16, 1,
102+
# key_as_bytes=0, d='md5', salt=None, i=1,
103+
# padding=1)
104+
# decipher = M2Crypto.EVP.Cipher('aes_128_cfb', 'k' * 32, 'i' * 16, 0,
105+
# key_as_bytes=0, d='md5', salt=None, i=1,
106+
# padding=1)
103107

104108
cipher = Salsa20Cipher('salsa20-ctr', 'k' * 32, 'i' * 8, 1)
105109
decipher = Salsa20Cipher('salsa20-ctr', 'k' * 32, 'i' * 8, 1)
@@ -108,15 +112,15 @@ def test():
108112
print 'start'
109113
start = time.time()
110114
while pos < len(plain):
111-
l = random.randint(100, 16384)
115+
l = random.randint(100, 32768)
112116
c = cipher.update(plain[pos:pos + l])
113117
results.append(c)
114118
pos += l
115119
pos = 0
116120
c = ''.join(results)
117121
results = []
118122
while pos < len(plain):
119-
l = random.randint(100, 16384)
123+
l = random.randint(100, 32768)
120124
results.append(decipher.update(c[pos:pos + l]))
121125
pos += l
122126
end = time.time()

0 commit comments

Comments
 (0)