Python implements simple encryption and decryption of files

Table of contents

1. Basic knowledge

2. Encryption and decryption algorithm

1. Import the runtime library

2. Define the key generation function

3. Define encryption and decryption units

4. Encrypt files

5. Decrypt files

3. Test


1. Basic knowledge

The XOR operator in Python is ^, also recorded as XOR. The result of bitwise XOR is: when the values ​​are the same, the XOR is 0, when the values ​​are different, the XOR is 1. There are four situations in total: 0 ^ 0 = 0 , 0 ^ 1 = 1, 1 ^ 0 = 1, 1 ^ 1 = 0. Simple encryption and decryption operations can be performed on files using XOR.

Encryption operation: First convert the file into a binary number, and then randomly generate a key with the same length as the binary number. Perform an XOR operation on the binary number of the file and the key to obtain the encrypted binary number and store it as an encrypted file. .

Decryption operation: XOR the encrypted binary file with the key to obtain the original binary number, and then restore the original binary number to the file.

2. Encryption and decryption algorithm

1. Import the runtime library

import json
from pathlib import Path
from secrets import token_bytes
import argparse

2. Define the key generation function

def random_key(length):
    key = token_bytes(nbytes=length)            #根据指定长度生成随机密钥
    key_int = int.from_bytes(key, 'big')        #将byte转换为int
    return key_int

3. Define encryption and decryption units

def encrypt(raw):                                    #加密单元
    raw_bytes = raw.encode()                         #将字符串编码成字节串
    raw_int = int.from_bytes(raw_bytes, 'big')       #将byte转换成int
    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') #将int转换回byte
    return decrypted_bytes.decode()                          #解码后返回

4. Encrypt files

def encrypt_file(path, key_path=None, *, encoding='utf-8'):    #参数path指定文件地址
    path = Path(path)
    cwd = path.cwd() / path.name.split('.')[0]
    path_encrypted = cwd / path.name
    if key_path is None:
        key_path = cwd / 'key'
    if not cwd.exists():
        cwd.mkdir()
        path_encrypted.touch()
        key_path.touch()

    //打开文件并将内容写入
    with path.open('rt', encoding=encoding) as f1, \
            path_encrypted.open('wt', encoding=encoding) as f2, \
            key_path.open('wt', encoding=encoding) as f3:
        encrypted, key = encrypt(f1.read())
        json.dump(encrypted, f2)
        json.dump(key, f3)

5. Decrypt files

def decrypt_file(path_encrypted, key_path=None, *, encoding='utf-8'):
    path_encrypted = Path(path_encrypted)
    cwd = path_encrypted.cwd()
    path_decrypted = cwd / 'decrypted'
    if not path_decrypted.exists():
        path_decrypted.mkdir()
        path_decrypted /= path_encrypted.name
        path_decrypted.touch()
    if key_path is None:
        key_path = cwd / 'key'
    with path_encrypted.open('rt', encoding=encoding) as f1, \
            key_path.open('rt', encoding=encoding) as f2, \
            path_decrypted.open('wt', encoding=encoding) as f3:
        decrypted = decrypt(json.load(f1), json.load(f2))
        f3.write(decrypted)

3. Test

Place the file to be encrypted in the same directory as the py file and run the following to encrypt 1.txt.

encrypt_file("D:/PyCharm Community Edition 2021.3.2/Workplace/encryption/1.txt")

 Place the file and key to be decrypted in the same directory as the py file, and run the following to decrypt and restore 1.txt.

decrypt_file("D:/PyCharm Community Edition 2021.3.2/Workplace/encryption/1.txt")

Guess you like

Origin blog.csdn.net/SAGIRIsagiri/article/details/124541807