Reputation: 719
I got a file that encrypted with rc4 key.
I got that key and want to decrypt it with a python script.
How can I do this?
Upvotes: 4
Views: 29937
Reputation: 2672
PyCryptodome does it nowadays: 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')
Upvotes: 4
Reputation: 1651
Found the following after a 3 second Google search: http://www.emoticode.net/python/python-implementation-of-rc4-algorithm.html
Modified it thusly:
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)
Not sure if this will work, as you did not give us any data to work with.. next time please post an example of the data, the code you have already tried, and what errors you are getting.
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)
Upvotes: 5