1 year ago
#181200
Pedro
Decrypt file with Python
I am having a problem when decrypting a file that has information appended. The steps I take are the following. I encrypt a file and append a string (converted to bytes) after encryption and write to the file. When I decrypt the file I strip the bytes from the back of the file and proceed to decryption, then I write to the file but the file is corrupted, when I do this same process without appending the bytes it works fine. What could I be missing? Any help would be greatly appreciated!
def salsa_encrypt(data):
cipher = '6d38d2f2d0318e53712156ad06f6813349be934a83b15f723f039a82fa3f2fb9'
key = bytes.fromhex(cipher)
nonce_iv = '1c5cd305932039f5'
nonce = bytes.fromhex(nonce_iv)
cipher = Salsa20.new(key=key, nonce=nonce)
encrypted = cipher.encrypt(data)
return encrypted
def encrypt():
string = '50567A8ED6FB1A33F484E62F9280F58F9B7D2DD369F613306970F53331FDBCA41DFF00474529A2BD3DF4A9B9192709B2BF0C890D9D1A746FE61A39CD3F5F28FD89B3303B402D538BF2EE57CCE3B87998BB12B40D35AD1F552F23F7E6599F4BC2FAAE6110033D0EBB70BEF4A5109CB02E1331491E73C4905DBBF51D609A8CFF55B267C5F89EE6D19995C831E26E8D531D107D388133EEC895313F33493C1BE92E73C32509F5BB386B0CFAC216E6DC1C0E36A987F5BF55860FBC43B76EA11DDF036AD3547C8728804CA67E758352587F00094F60CABBCFB4C9D76429DC00000000000000009125B680'
append = bytes.fromhex(string)
path_store = os.getcwd() + "\\" + "testing"
path = os.listdir(os.getcwd() + "\\" + "testing")
for file in path:
print('[*] File - ', file)
try:
extension = '.copy'
fhi = open(path_store + '\\' + file, 'rb')
fho = open(path_store + '\\' + file + extension, 'wb')
chunk = fhi.read()
ciphertext = salsa_encrypt(chunk)
fho.write(ciphertext + append)
fhi.close()
fho.close()
except Exception:
print('[-] Could not open: ', file)
pass
return
And here is the decryption script:
def salsa_decrypt(data):
cipher = 'edd8a9f8e446c41b312649df34f5237740db6b2a5923a5a44300389c9c3d3f54'
key = bytes.fromhex(cipher)
nonce_iv = '094f60cabbcfb4c9'
nonce = bytes.fromhex(nonce_iv)
cipher = Salsa20.new(key=key, nonce=nonce)
decrypted = cipher.decrypt(data)
return decrypted
def main():
path_store = os.getcwd() + "\\" + "testing"
path = os.listdir(os.getcwd() + "\\" + "testing")
for file in path:
print('[*] File - ', file)
try:
with open(path_store + '\\' + file, 'rb') as f:
text = f.read()
size = len(text)
chunk = text[:size - 232]
decrypted = salsa_decrypt(chunk)
fho = open(path_store + '\\' + 'restored.jpg', 'wb')
fho.write(decrypted)
fho.close()
except Exception:
print('[-] Could not open: ', file)
pass
UPDATE: I found the solution in another post, I will leave it here in case it helps anybody: Python - Simplest method of stripping the last byte from a file?
python
file
encryption
pycrypto
0 Answers
Your Answer