使用python解密文件

时间:2016-12-06 10:14:21

标签: python python-2.7 encryption caesar-cipher

嘿伙计们我已经开始做一些python编码了,我能够创建这个程序来解密我提供的加密文本,使用我提供的密钥可以有人帮助我将文本解密更改为文件解密。 / p>

import sys

def decrypt(cipher, key):

plain = ""
for index in range(len(cipher)):
    if cipher[index].isalpha():

        if cipher[index].isupper():
            plain = plain + chr((ord(cipher[index]) - 64 - key) % 26 + 64)


        elif cipher[index].islower():
            plain = plain + chr((ord(cipher[index]) - 96 - key) % 26 + 96)

    else:
            plain = plain + cipher[index]

return plain

in_filename = sys.argv[1]
key = int(sys.argv[2])
out_filename = sys.argv[3] 

with open(in_filename, "r") as f:
    encrypted = f.read()

decrypted = decrypt(encrypted, key)

with open(out_filename, "w+") as f:
    f.write(decrypted)




cipher = sys.argv[1]
plain = sys.argv[1]
key = int(sys.argv[2])
print('{}'.format(cipher))
print('{}'.format(decrypt(cipher, key)))

我可以通过在终端

中键入此命令来使用我当前的程序

python cipher.py' Yaholy' 7将这个词解密为“反而”

1 个答案:

答案 0 :(得分:0)

您可以使用已有的内容,只需从文件中读取,然后将结果写回。

in_filename = sys.argv[1]
key = int(sys.argv[2])
out_filename = sys.argv[3] # if you want

with open(in_filename, "r") as f:
    encrypted = f.read()

decrypted = decrypt(encrypted, key)

with open(out_filename, "w+") as f:
    f.write(decrypted)

print(decrypted) # if you don't want to save to a file

然后你可以用python cipher.py encrypted.txt 7 decrypted.txt

来调用它