因为我项目主要是python写的,遇到网站自研加密算法,并且加密代码最多几百行时,我都会翻译成python。
js、Java、c++的移位操作很简单,主要说下python的,100行Java加密代码翻译了我整整一天多....
import ctypes
def int_overflow(val):
maxint = 2147483647
if not -maxint-1 <= val <= maxint:
val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1
return val
def unsigned_right_shitf(n, i):
if n < 0:
n = ctypes.c_uint32(n).value
if i < 0:
return -int_overflow(n << abs(i))
return int_overflow(n >> i)
这两个方法从https://www.zhangshengrong.com/p/bYXxZBVdaZ/大佬博客上复制过来的,很nice。
>>是带符号右移,int_overflow(123456789 << 20)
>>>是无符号右移, unsigned_right_shitf(-1, 20)
还遇到了Java的int转byte,也是让我捣鼓了半天。
python实现如下:
def int2byte(n):
if -256 < n < 256:
return n
return int2byte(n % -256) if n > 0 else int2byte(n % 256)
还有Java byte数组转base64:
def bytes2b64(buffers):
buffers = [b & 0xff for b in buffers]
return base64.b64encode(bytes(buffers)).decode()
byte数组转hex:
def bytes2str(buffers):
return ''.join([format(b & 0xff, 'x') for b in buffers])