Search code examples
pythonencryptionpycryptodome

crypt with AES 256 2 files inside txt


i have a problem, i got 2 txt files inside other txt, the txt is called secrets.txt ,

the code is the next...

import os
import random
import hashlib
import socket
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

key = b'0123456789abcdef'

pathfiles = open('secrets.txt', 'r')
pathfiles = pathfiles.readlines()

print(pathfiles)
for archvi in pathfiles:
    archvi = archvi.rstrip()
    IV = 16 * b'\x00'
    mode = AES.MODE_CBC
    cipher = AES.new(key, mode, IV=IV)
    openfile = open(archvi, 'rb')
    readfile = openfile.readlines()
    readfile = readfile
    openfile.close()
    encoding = cipher.encrypt(readfile)
    os.system("rm ")+ archvi
    openfile2 = open(archvi, 'wb')
    openfile2.write(encoding)
    openfile2.close()

inside the file secrets.txt are the next content....

/home/kali/Desktop/SecretMessage.txt
/home/kali/Desktop/hello.png

output when i execute my python file is

Traceback (most recent call last):
  File "/home/kali/Desktop/holis.py", line 31, in <module>
    encoding = cipher.encrypt(readfile)
  File "/usr/local/lib/python3.9/dist-packages/Crypto/Cipher/_mode_cbc.py", line 178, in encrypt
    c_uint8_ptr(plaintext),
  File "/usr/local/lib/python3.9/dist-packages/Crypto/Util/_raw_api.py", line 143, in c_uint8_ptr
    raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <class 'list'> cannot be passed to C code

how i can fix it?


Solution

  • Although your call to os.system was wrong, you don't need to remove the file if you are immediately going to open it for writing. That will replace the older file.

    import os
    from Crypto.Cipher import AES
    
    key = b'0123456789abcdef'
    
    pathfiles = open('secrets.txt', 'r').readlines()
    print(pathfiles)
    for archvi in pathfiles:
        archvi = archvi.rstrip()
        IV = b'\x00' * 16
        mode = AES.MODE_CBC
        cipher = AES.new(key, mode, IV=IV)
        readfile = open(archvi, 'rb').read()
        encoding = cipher.encrypt(readfile)
        open(archvi, 'wb').write(encoding)