Skip to content

Instantly share code, notes, and snippets.

@zhu327
Created February 23, 2018 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhu327/009d8bf4db2a7142e21f13fa04a483a6 to your computer and use it in GitHub Desktop.
Save zhu327/009d8bf4db2a7142e21f13fa04a483a6 to your computer and use it in GitHub Desktop.
OpenSSL RC4
# coding:utf-8
class RC4:
def __init__(self,public_key = None):
if not public_key:
public_key = 'none_public_key'
self.public_key = public_key
self.index_i = 0;
self.index_j = 0;
self._init_box()
def _init_box(self):
"""
初始化 置换盒
"""
self.Box = range(256)
key_length = len(self.public_key)
j = 0
for i in range(256):
index = ord(self.public_key[(i % key_length)])
j = (j + self.Box[i] + index ) % 256
self.Box[i],self.Box[j] = self.Box[j],self.Box[i]
def do_crypt(self,string):
"""
加密/解密
string : 待加/解密的字符串
"""
out = []
for s in string:
self.index_i = (self.index_i + 1) % 256
self.index_j = (self.index_j + self.Box[self.index_i]) % 256
self.Box[self.index_i], self.Box[self.index_j] = self.Box[self.index_j], self.Box[self.index_i]
r = (self.Box[self.index_i] + self.Box[self.index_j]) % 256
R = self.Box[r] # 生成伪随机数
out.append(chr(ord(s) ^ R))
return ''.join(out)
def rc4(s, key):
r = RC4(key)
return r.do_crypt(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment