如何使用Python解密用rc4加密的文件?

时间:2015-04-13 14:24:26

标签: python encryption rc4-cipher

我有一个用rc4密钥加密的文件。

我得到了那个密钥,想用python脚本解密它。

我该怎么做?

2 个答案:

答案 0 :(得分:4)

在3秒Google搜索后发现以下内容:http://www.emoticode.net/python/python-implementation-of-rc4-algorithm.html

因此修改了它:

import base64

data = base64.b64decode("<encrypted file contents>")
key = "<rc4 key>"

S = range(256)
j = 0
out = []

#KSA Phase
for i in range(256):
    j = (j + S[i] + ord( key[i % len(key)] )) % 256
    S[i] , S[j] = S[j] , S[i]

#PRGA Phase
i = j = 0
for char in data:
    i = ( i + 1 ) % 256
    j = ( j + S[i] ) % 256
    S[i] , S[j] = S[j] , S[i]
    out.append(chr(ord(char) ^ S[(S[i] + S[j]) % 256]))

print ''.join(out)

不确定这是否有效,因为您没有向我们提供任何数据...下次请发布数据示例,您已经尝试过的代码以及您获得的错误。


编辑 - 使用文件

import base64

with open("/path/to/file.txt", "r") as encrypted_file:
    data = base64.b64decode(encrypted_file.read())
key = "<rc4 key>"

S = range(256)
j = 0
out = []

#KSA Phase
for i in range(256):
    j = (j + S[i] + ord( key[i % len(key)] )) % 256
    S[i] , S[j] = S[j] , S[i]

#PRGA Phase
i = j = 0
for char in data:
    i = ( i + 1 ) % 256
    j = ( j + S[i] ) % 256
    S[i] , S[j] = S[j] , S[i]
    out.append(chr(ord(char) ^ S[(S[i] + S[j]) % 256]))

decrypted_text = ''.join(out)
with open('decrypted.txt', 'w') as decrypted_file:
    decrypted_file.write(decrypted_text)

答案 1 :(得分:1)

PyCryptodome现在已经做到了:https://pycryptodome.readthedocs.io/en/latest/src/cipher/arc4.html

from Crypto.Cipher import ARC4
key = b'Very long and confidential key'
cipher = ARC4.new(key)
msg = cipher.encrypt(b'Open the pod bay doors, HAL')