SoFunction
Updated on 2024-10-29

Python encrypted word documents in detail

Python encrypts word documents

Let's start by understanding what anomalies are. Simply put, if a, b two values are not the same, the result is 1. If a, b two values are the same, the result is 0. Let's simply comb through the code idea. The code is divided into two parts, encryption and decryption.

1. Encryption

Convert the file to binary format and then generate a random key of equal length to perform an iso operation to get the encrypted binary file. The data we need to keep in this step are, the encrypted file and the randomly generated key, of course they are all some binary numbers.

2. Decryption

This step is simple, we encrypted file and the previous randomly generated key and then perform an iso-ortho operation, you can get the original binary number, and then we convert it to text can be.

OK, the idea is generally clear, we need two programs, the encryption program to receive str parameters, run the completion of the output will be encrypted binary word document, and used to decrypt the binary key. Decryption program needs to receive two int parameters, respectively, for the encryption program output of the two binary content, or after the output of the original text. Then, on the code.

Encryption code:

from secrets import token_bytes
from docx import Document
import docx
import time
​
def random_key(length):
    # token_bytes, the function accepts an int argument to specify the length of the random byte string.
    # int.from_bytes converts the byte string to int, which is the binary number we need
    key = token_bytes(nbytes=length)
    key_int = int.from_bytes(key, 'big')
    return key_int
​
def encrypt(raw):
    raw_bytes = ()
    The # parameter big is meant to be in positive order, and little outputs the reverse order.
    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()
​
def encrypt_file(path, key_path=None,):
    document = Document(path)
    all_paragraphs = 
    file = ()
    file2 = ()
​
    jkl = input('Please enter the name of the file you wish to save:') + '.docx'
​
    for paragraph in all_paragraphs:
        # Print the text of each paragraph
        zz,key = encrypt()
​
        #print('Encryption:',zz)
        #print('key:', key)
​
        file.add_paragraph(str(zz))
        (jkl)
​
        file2.add_paragraph(str(key))
        ("")
​
print('From the Funny Institute!')
print('Only English filenames are supported.')
chenggong = encrypt_file(input('Please enter the name of the file to be encrypted:'))
print("Completed! Automatic shutdown in ten seconds.")
(10)
# Generate encrypted files

The encode method encodes the string into a byte string. int.from_bytes function converts the byte string into an int object. Finally, the binary object and the random key are used to obtain the encrypted text.

Decryption code:

from secrets import token_bytes
from docx import Document
import docx
import time
​
def random_key(length):
    # token_bytes, the function accepts an int argument to specify the length of the random byte string.
    # int.from_bytes converts the byte string to int, which is the binary number we need
    key = token_bytes(nbytes=length)
    key_int = int.from_bytes(key, 'big')
    return key_int
​
def encrypt(raw):
    raw_bytes = ()
    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 = 
​
    do2 = Document('')
    all_p= 
​
    for i in all_paragraphs:
        #str to int
        jiam = int()
        (jiam)
​
        #print('Encryption:',jiam)
    #print(jjj)
​
    for k in all_p:
        #str to int
        key = int()
        (key)
​
        #print('key:',key)
    #print(kkk)
​
    cc = zip(jjj,kkk)
    res = list(cc)
    return res
# Pass in a tuple, or two int's.
print('From the Funny Institute!')
print('Warning, modification of key file names is strictly forbidden!!!')
print('Enter the filename directly without a format suffix.')
rr1 = decrypt_file(input("Please enter the file name of the file to be cracked(restricted to.docxfile):")+'.docx')
​
file = ()
for i in rr1:
    ff = decrypt(*i)
    #print(ff)
    #print(type(ff))
    file.add_paragraph(ff)
("")
print('Decryption complete, please extract files in current folder!')
print(''Automatically shut down in ten seconds!'')
(10)

We need to package the two programs into exe. the binary word document obtained by running the encryption program can be given to other people, but the key must be kept by yourself. When others meet your requirements, we can give him the key and decryption program. Note that it is only valid for docx files and you can't change the name of the key file, or it will report an error and the decryption will fail.

Run results:

Original word document.

在这里插入图片描述

Encrypted:

在这里插入图片描述

The generated key key:

在这里插入图片描述

The encrypted file and the generated key, after being placed in the decryption program folder, will look like the following. We get the original file, the beauty of it is that all the first line indentation has disappeared and it has become left-justified.

在这里插入图片描述

The same file, when re-encrypted, will get a different encryption file and key. So if the encrypted file and key don't match, it can't be decrypted even if their source files are the same. In addition the key is lost and the encrypted file will never be decrypted.

summarize

That's all for this post, I hope it helped you and I hope you'll check back for more from me!