用 Python 加解密日常文件

生活中,有时候我们需要对一些重要的文件进行加密,Python 提供了诸如 hashlib,base64 等便于使用的加密库。

一、基础知识

在 Python 中异或操作符为:^,也可以记作 XOR。按位异或的意思是:相同值异或为 0,不同值异或为 1。具体来讲,有四种可能:0 ^ 0 = 0,0 ^ 1 = 1, 1 ^ 0 = 1, 1 ^ 1 = 0。我们还可总结出规律(A 为 0 或 1):0 和 A 异或为 A本身;1 和 A 异或为 A 反。

让我们想看看一位二进制数满足的性质:

一位二进制数与自身的异或值为 0
b ^ b = 0

异或操作满足交换律
a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c

0 与 a 的异或为 a
(a ^ b) ^ b = a ^ (b ^ b) = a ^ 0 = a

易知,对任意长二进制数都满足上述性质。

二、加密操作

首先将文件转换成二进制数,再生成与该二进制数等长的随机密钥,将二进制数与密钥进行异或操作,得到加密后的二进制数。

三、解密操作

将加密后的二进制程序与密钥进行异或操作,就得到原二进制数,最后将原二进制数恢复成文本文件。

四、生成随机密钥

secrets 库是 Python 3.6 引入的伪随机数模块,适合生成随机密钥。token_bytes 函数接受一个 int 参数,用于指定随机字节串的长度。int.from_bytes 把字节串转换为 int,也就是我们需要的二进制数。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from secrets import token_bytes
def random_key(length):
    key = token_bytes(nbytes=length)
    key_int = int.from_bytes(key, 'big')  #必须为big或者little
    return key_int

五、加密单元

encrypt 函数接受一个 str 对象,返回元组 (int, int)。通过 encode 方法,我们将字符串编码成字节串。int.from_bytes 函数将字节串转换为 int 对象。最后对二进制对象和随机密钥进行异或操作,就得到了加密文本。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from secrets import token_bytes
def random_key(length):
    key = token_bytes(nbytes=length)
    key_int = int.from_bytes(key, 'big')  #必须为big或者little
    return key_int

def encrypt(raw):
    raw_bytes = raw.encode()
    raw_int = int.from_bytes(raw_bytes, 'big')   #必须为big或者little
    key_int = random_key(len(raw_bytes))
    return raw_int ^ key_int, key_int

六、解密单元

decrypt 接受两个 int 对象,分别为加密文本和随机密钥。首先对两者进行异或操作,计算解密出来的 int 对象所占比特数。decrypted.bit_length 函数得到的是二进制数的位数,除以 8 可以得到所占比特大小。为了防止,1 ~ 7 位的二进制数整除 8 得到 0,所以要加上 7,然后再进行整除 8 的操作。使用 int.to_bytes 函数将解密之后的 int 的对象转换成 bytes 对象。最后通过 decode 方法,将字节串转换成字符串。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

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()

利用上述函数,我们可以很轻松对文本文件进行加密、解密操作。

>>> raw = '画图省识春风面,环珮空归夜月魂'
>>> encrypted = encrypt(raw)
>>> encrypted
(217447100157746604585...,
 9697901906831571319...)
>>> decrypt(*encrypted)
'画图省识春风面,环珮空归夜月魂'

七、加密文本文件

path 为待加密文件的地址,如果不指定密钥地址,则在该目录下新建目录和文件。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import json
from pathlib import Path
from secrets import token_bytes
def random_key(length):
    key = token_bytes(nbytes=length)
    key_int = int.from_bytes(key, 'big')  #必须为big或者little
    return key_int

def encrypt(raw):
    raw_bytes = raw.encode()
    raw_int = int.from_bytes(raw_bytes, 'big')   #必须为big或者little
    key_int = random_key(len(raw_bytes))
    return raw_int ^ key_int, key_int

def encrypt_file(path, key_path=None, *, encoding='utf-8'):
    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:
        with path_encrypted.open('wt', encoding=encoding) as f2:
            with key_path.open('wt', encoding=encoding) as f3:
                encrypted, key = encrypt(f1.read())
                json.dump(encrypted, f2)
                json.dump(key, f3)

八、解密文件

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import json
from pathlib import Path

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 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:
        with key_path.open('rt', encoding=encoding) as f2:
            with path_decrypted.open('wt', encoding=encoding) as f3:
                decrypted = decrypt(json.load(f1), json.load(f2))
                f3.write(decrypted)

猜你喜欢

转载自blog.csdn.net/m0_37886429/article/details/90636326