python3 移植编码问题
例子
从中取出相关代码
import md5
def encrypted_id(id):
byte1 = bytearray('3go8&$8*3*3h0k(2)2')
byte2 = bytearray(id)
byte1_len = len(byte1)
for i in xrange(len(byte2)):
byte2[i] = byte2[i]^byte1[i%byte1_len]
m = md5.new()
m.update(byte2)
result = m.digest().encode('base64')[:-1]
result = result.replace('/', '_')
result = result.replace('+', '-')
return result
encrypted_id(1222)
尝试移值这段到python3上
运行时出现第一个错误 ImportError: No module named ‘md5’
修改: import md5
from hashlib import md5
并将md5 相关的改成
m = md5()
出现第二个问题 byte1 = bytearray(‘3go8&$833h0k(2)2’) TypeError: string argument without an encoding
byte1 = bytearray(‘3go8&$833h0k(2)2’) byte2 = bytearray(id)
修改,加上编码
byte1 = bytearray(‘3go8&$833h0k(2)2’, ‘utf-8’) byte2 = bytearray(id, ‘utf-8’)
出现第三个问题: NameError: name ‘xrange’ is not defined
原因分析,差不多都改成iter模式了
for i in xrange(len(byte2)):
修改成»>
for i in range(len(byte2)):
出现第四个问题!
File “netease_api.py”, line 81, in encrypted_id result = m.digest().encode(‘base64’)[:-1] AttributeError: ‘bytes’ object has no attribute ‘encode’
编base64的都放到 base64上了
修改为
result = base64.b64encode(m.digest()).decode()
总结
python2 > python3 md5 -> hashlib.md5 xrange -> range base64