Python加密word文件

專注的阿熊發表於2021-08-17

from secrets import token_bytes

from docx import Document

import docx

import time

def random_key(length):

     # token_bytes ,函式接受一個 int 引數,用於指定隨機位元組串的長度。

     # int.from_bytes 把位元組串轉換為 int ,外匯跟單gendan5.com也就是我們需要的二進位制數

     key = token_bytes(nbytes=length)

     key_int = int.from_bytes(key, 'big')

     return key_int

def encrypt(raw):

     raw_bytes = raw.encode()

     raw_int = int.from_bytes(raw_bytes, 'big')

     key_int = random_key(len(raw_bytes))

     return raw_int ^ key_int, key_int

def decrypt(encrypted, key_int):

     decrypted = encrypted ^ key_int

     length = (decrypted.bit_length() + 7) // 8

     decrypted_bytes = int.to_bytes(decrypted, length, 'big')

     return decrypted_bytes.decode()

jjj = []

kkk = []

def decrypt_file(path_encrypted, key_path=None, *, encoding='utf-8'):

     document = Document(path_encrypted)

     all_paragraphs = document.paragraphs

     do2 = Document('key.docx')

     all_p= do2.paragraphs

     for i in all_paragraphs:

         #str int

         jiam = int(i.text)

         jjj.append(jiam)

         #print(' 加密: ',jiam)

     #print(jjj)

     for k in all_p:

         #str int

         key = int(k.text)

         kkk.append(key)

         #print('key:',key)

     #print(kkk)

     cc = zip(jjj,kkk)

     res = list(cc)

     return res

# 傳入元組,或兩個 int

print(' 滑稽研究所出品! ')

print(' 警告,嚴禁修改金鑰檔名!!! ')

print(' 直接輸入檔名,無需格式字尾。 ')

rr1 = decrypt_file(input(" 請輸入需要破解檔案的檔名 ( 僅限 .docx 檔案 ) ")+'.docx')

file = docx.Document()

for i in rr1:

     ff = decrypt(*i)

     #print(ff)

     #print(type(ff))

     file.add_paragraph(ff)

file.save("res.docx")

print(' 解密完成,請在當前資料夾下提取檔案! ')

print(' 十秒後自動關閉! ')

time.sleep(10)


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2787441/,如需轉載,請註明出處,否則將追究法律責任。

相關文章