利用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()

你可能感兴趣的:(密码)