RC4 with Python
import struct,sys,os,binascii
"""
RC4加密算法
16*16 S盒
加密单元:short
"""
def RC4(pkey,keylen,pin,dlen):
N=65536
S = list(range(N))
j = 0
for i in range(N):
j = (j + S[i] + pkey[i%keylen])%N
temp = S[i]
S[i] = S[j]
S[j] = temp
i = j = 0
pout= b''
for x in range(dlen):
i = i+1
j = (j + S[i])%N
temp = S[i]
S[i] = S[j]
S[j] = temp
pout += struct.pack('H',pin[x]^S[(S[i]+S[j])%N])
return(pout)
"""
def RC4(pkey,keylen,pin,dlen):
# bytes->short
def coding(data):
if(len(data)%2):
data+=b'\0'
dlen = len(data)//2
return(struct.unpack(str(dlen)+'H',data))
def coding(data):
# short->bytes
def unCoding(data):
d=b''
for i in range(len(data)):
d += struct.pack('H',data[i])
return(d)
def unCoding(data):
#产生32字节密钥
def CreaTKEy(Keyt):
pl = len(Keyt)
Key=b''
r=0
for i in range(32):
k=(Keyt[r%pl]+i)%256
Key+= struct.pack('B',k)
r+=1
return Key
def CreaTKEy(Keyt):
#更新密钥
def UpdataKey(Keyt):
Key = unCoding(Keyt)
#循环左移
Key = Key[1:] + struct.pack('B',Key[0])
tem=0
#求和
for i in range(len(Key)):
tem += Key[i];
Keyo=b''
#Xor
for i in range(len(Key)):
Keyo += struct.pack('B',(Key[i]^tem)%256)
tem += Keyo[i]>>3
tem = tem % 256
return(Coding(Keyo))
def UpdataKey(Keyt):
if __name__ == '__main__':
相关文章