apppublic/appPublic/rc4.py

66 lines
1.7 KiB
Python
Raw Normal View History

2019-07-16 16:33:07 +08:00
# -*- coding: utf-8 -*-
import random, base64
from hashlib import sha1
class RC4:
2019-08-12 11:55:18 +08:00
def __init__(self,data_coding='utf8'):
2019-07-16 16:33:07 +08:00
self.bcoding = 'iso-8859-1'
self.dcoding = data_coding
self.salt = b'AFUqx9WZuI32lnHk'
def _crypt(self,data,key):
"""RC4 algorithm return bytes"""
if type(data)==type(''):
data = data.encode(self.dcoding)
x = 0
box = [i for i in range(256) ]
for i in range(256):
x = (x + box[i] + key[i % len(key)]) % 256
box[i], box[x] = box[x], box[i]
x = y = 0
out = []
for char in data:
x = (x + 1) % 256
y = (y + box[x]) % 256
box[x], box[y] = box[y], box[x]
out.append(chr(char ^ box[(box[x] + box[y]) % 256]))
return ''.join(out).encode(self.bcoding)
2019-08-12 11:55:18 +08:00
def encode(self,data, key,encode=base64.b64encode, salt_length=16):
2019-07-16 16:33:07 +08:00
"""RC4 encryption with random salt and final encoding"""
2019-08-12 11:55:18 +08:00
akey = key.encode(self.bcoding)
a = sha1(akey + self.salt)
2019-07-16 16:33:07 +08:00
k = a.digest()
data = self.salt + self._crypt(data, k)
if encode:
data = encode(data)
return data.decode(self.dcoding)
2019-08-12 11:55:18 +08:00
def decode(self,data, key,decode=base64.b64decode, salt_length=16):
2019-07-16 16:33:07 +08:00
"""RC4 decryption of encoded data"""
2019-08-12 11:55:18 +08:00
akey = key.encode(self.bcoding)
2019-07-16 16:33:07 +08:00
if decode:
data = decode(data)
salt = data[:salt_length]
2019-08-12 11:55:18 +08:00
a = sha1(akey + self.salt)
2019-07-16 16:33:07 +08:00
k = a.digest() #.decode('iso-8859-1')
r = self._crypt(data[salt_length:], k)
return r.decode(self.dcoding)
if __name__=='__main__':
2019-07-16 17:00:48 +08:00
# 需要加密的数据长度没有限制
2019-07-16 16:33:07 +08:00
# 密钥
2019-07-16 17:00:48 +08:00
data="231r3 feregrenerjk gkht324g8924gnfw k;ejkvwkjerv"
2019-07-16 16:33:07 +08:00
key = '123456'
2019-08-12 11:55:18 +08:00
rc4 = RC4()
2019-07-16 16:33:07 +08:00
print(data)
# 加码
2019-08-12 11:55:18 +08:00
encoded_data = rc4.encode(data,key)
2019-07-16 16:33:07 +08:00
print(encoded_data,len(encoded_data) )
# 解码
2019-08-12 11:55:18 +08:00
decoded_data = rc4.decode(encoded_data,key)
2019-07-16 17:00:48 +08:00
print(decoded_data)