Python 实现RC4加解密
核心原理如下:
- 导入包ARC4 其中Crypto如果没有可以网上搜索安装
- 主要就是利用ARC4的new(传入key) 返回一个rc4对象
- rc4对象在调用加密或者解密函数. 注意key必须是 bytes类型.如果不是要转换为bytes
- 对于base64编码过的程序请先解码.然后再用 代码如下:
import sys
import base64
from Crypto.Cipher import ARC4
class rc4util():
def __init__(self,key):
if isinstance(key,str):
self.__keyGen = key.encode()
elif isinstance(key,bytes):
self.__keyGen = key
def __encrypt(self,data)->bytes:
rc4 = ARC4.new( self.__keyGen)
res = rc4.encrypt(data)
return res
def __decrypt(self,data)->bytes:
rc4 = ARC4.new(self.__keyGen)
res = rc4.decrypt(data)
#res = base64.b64encode(res)
return res
def EncryptFileToDst(self,src,dst)->bool:
with open(src,"rb") as f_read:
data = f_read.read()
res = self.__decrypt(data)
with open(dst,"wb") as f_write:
f_write.write(res)
return True
def Entry(src,dst):
key = bytes([0xD8, 0x7e, 0x54, 0x32, 0x61, 0x47, 0x33, 0x55]);
rc4 = rc4util(key)
bret = rc4.EncryptFileToDst(src,dst)
if bret:
print("加密成功")
else:
print("加密失败")
def Decry(src,dst):
key = bytes([0xD8, 0x7e, 0x54, 0x32, 0x61, 0x47, 0x33, 0x55]);
rc4 = rc4util(key)
bret = rc4.EncryptFileToDst(src,dst)
if bret:
print("加密成功")
else:
print("加密失败")
if __name__ == "__main__":
src = r"xxxsrcFile" #这里是读取src文件数据,然后对其进行加密.加密的结果写入到dst文件中
dst = r"xxxdstFile"
Entry(src,dst);