【问题标题】:How to decrypt a file that encrypted with rc4 using Python?如何使用 Python 解密使用 rc4 加密的文件?
【发布时间】:2015-04-13 14:24:25
【问题描述】:

我得到了一个使用 rc4 密钥加密的文件。

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

我该怎么做?

【问题讨论】:

标签: python encryption rc4-cipher


【解决方案1】:

在 Google 搜索 3 秒后发现以下内容: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)

【讨论】:

  • 是的,我也找到了。但是该脚本在读取文件和解密时存在问题。
  • Python 可以读取文件的内容,如果你告诉它的话。 with open('/path/to/file.txt', 'r') as encrypted_file:
  • 读取文件有问题。文件类型是 DAT 文件而不是 txt。我收到以下错误: Traceback(最近一次调用最后一次):文件“decrypt.py”,第 4 行,在 data = base64.b64decode(encrypted_file.read()) 文件“C:\Python27\lib\base64 .py",第 76 行,在 b64decode 中引发 TypeError(msg) TypeError: Incorrect padding
  • 啊,听起来您的文件已损坏。如果您有权访问 openssl(应该默认安装在您的 linux 机器上),请尝试使用它而不是 Python。 Base64 更智能。这是一个示例解码命令:openssl enc -d -base64 -in &lt;copy_paste_data_here&gt; -out binary_data
  • 滚动自己的加密是个坏主意。 PyCryptodome 的答案是正确的路径。 security.stackexchange.com/questions/18197/…
【解决方案2】:

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')

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2011-08-15
    相关资源
    最近更新 更多