利用python实现对txt文件的RC4加密解密

#!/usr/bin/env python
# -*- coding:utf-8 -*- 
# Author: feng
from Crypto.Cipher import ARC4
from Crypto.Hash import SHA
from Crypto.Random import get_random_bytes
import codecs
import os
import base64
import time




# 产生初始S盒
def S_box():
sbox = [i for i in range(0, 256)]
return sbox




# 产生T盒
def T_box(key):
key_list = [ord(i) for i in key]
t_box = [0 for i in range(256)]
length = len(key)
for i in range(256):
t_box[i] = key_list[i % length]
return t_box




# 利用T盒置换S盒
def rand_S(key):
s_BOX = S_box()
t_BOX = T_box(key)
j = 0
for i in range(256):
j = (j + s_BOX[i] + t_BOX[i]) % 256
s_BOX[i], s_BOX[j] = s_BOX[j], s_BOX[i]
return s_BOX




def stringToList(plain):
plain_List = [ord(x) for x in plain]
return plain_List




def ListToString(List):
msg = ''
for i in List:
msg += chr(i)
return msg




def PRGA(plainList, key):
i, j = 0, 0
time = 0
s_box = rand_S(key)
length = len(plainList)
key_list = []
while time <= length:
i = (i + 1) % 256
j = (j + s_box[i]) % 256
s_box[i], s_box[j] = s_box[j], s_box[i]
t = (s_box[j] + s_box[i]) % 256
k = s_box[t]
key_list.append(k)
time += 1
return key_list




def encrypto(key, route):
plainList = stringToList(readFile(route, 2))
key_list = PRGA(plainList, key)
bit_cipher = []
length = len(plainList)
for i in range(length):
bit_cipher.append(plainList[i] ^ key_list[i])
cipher = ListToString(bit_cipher)
writeFile(cipher)
return bit_cipher




def decrypto(cipherList, key, route):
plainList = stringToList(readFile(route))
key_list = PRGA(plainList, key)
bit_plain = []
length = len(plainList)
for i in range(length):
bit_plain.append(cipherList[i] ^ key_list[i])
plain = ListToString(bit_plain)
writeFile(plain, 2)
return plain




def readFile(route, sign=1):
if sign == 1:
with codecs.open(r'RC4密文.txt', 'r', 'utf-8') as f:
content = f.read()
return content
else:
with codecs.open(route, 'r', 'utf-8') as f:
return f.read()




def writeFile(string, sign=1):
if sign == 1:
with codecs.open(r"RC4密文.txt", 'w', "utf-8") as f:
f.write(string)
else:
with codecs.open(r"RC4明文.txt", 'w', 'utf-8') as f:
f.write(string)




def main():
route = input("请输入要加密的文件路径:")
skey = input("请输入秘钥:")
startTime = time.time()
cipher = encrypto(route=route, key=skey)
print("加密时间共%f s" % round(time.time() - startTime, 2))
startTime = time.time()
text = decrypto(cipher, skey, route)
print("解密时间共%f s" % round(time.time() - startTime, 2))




if __name__ == "__main__":
main()
  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值