首页 > 解决方案 > 带有密码学模块的python中的非对称加密重新调整空白文件

问题描述

我正在尝试使用非对称加密递归加密文件,但文件在解密后返回空白。密钥生成、打开密钥文件和粉碎旧文件似乎工作正常。

这是运行良好的密钥生成程序。它生成密钥并将它们保存到 2 个文件中:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
public_key = private_key.public_key()
pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())
print(pem)
with open('private_key.pem', 'wb') as f:
    f.write(pem)
pem = public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)
print(pem)
with open('public_key.pem', 'wb') as f:
    f.write(pem)

这是加密程序。它加载键,然后使用 glob 递归循环。然后它逐行加密文件写入新文件,并切碎旧文件:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
import glob
import os
import random

def getKey():
    with open("public_key.pem", "rb") as key_file:
        public_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend())
    return(public_key)
def shred(filePath):
    f = open(filePath, 'r')
    length = 0
    for i in f:
        length = length + 1
    f.close()
    f = open(filePath, 'w')
    for i in range(0, length):
        f.write(str(random.getrandbits(1024)))
    f.close()
    os.remove(filePath)
curDir = os.getcwd()
public_key = getKey()
print('begining encryption')
for x in glob.glob('C:\\Users\\Admin\\Documents\\code\\python\Deimos\\encrypt\\**\*', recursive=True):
    fullPath = os.path.join(curDir, x)
    fullNewF = os.path.join(curDir, x + '.aes')
    if os.path.isfile(fullPath):
            fileList = []
            f = open(fullPath, 'r')
            for i in f:
                fileList.append(i)
            f.close()
            encryptedFileList = []
            for i in range(0, len(fileList)):
                encryptedFileList.append(
                    public_key.encrypt(
                        fileList[i].encode(),
                        padding.OAEP(
                            mgf=padding.MGF1(algorithm=hashes.SHA256()),
                            algorithm=hashes.SHA256(),
                            label=None
                        )
                    )
                )
            f = open(fullNewF, 'w')
            for i in range(0, len(encryptedFileList)):
                f.write(str(encryptedFileList[i]))
            f.close()
            shred(fullPath)

这是解密程序。它打开密钥文件,使用 glob 递归循环,然后逐行解密文件,将加密文本写入新文件,然后粉碎旧文件。

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
import glob
import os
import random
def getKey():
    with open("private_key.pem", "rb") as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
            backend=default_backend()
        )
    return(private_key)
def shred(filePath):
    f = open(filePath, 'r')
    length = 0
    for i in f:
        length = length + 1
    f.close()
    f = open(filePath, 'w')
    for i in range(0, length):
        f.write(random.urandom(1024))
    f.close()
    os.remove(filePath)
curDir = os.getcwd()
private_key = getKey()
print('begining decryption')
for x in glob.glob('C:\\Users\\Admin\\Documents\\code\\python\Deimos\\encrypt\\**\*', recursive=True):
    fullPath = os.path.join(curDir, x)
    fullNewF = os.path.join(curDir, x.strip('.aes'))
    if (fullPath[-4:] == '.aes'):
            fileList = []
            f = open(fullPath, 'r')
            for i in f:
                fileList.append(i)
            f.close()
            decryptedFileList = []
            for i in range(0, len(fileList)):
                decryptedFileList.append(
                    private_key.decrypt(
                        fileList[i],
                        padding.OAEP(
                            mgf=padding.MGF1(
                                algorithm=hashes.SHA256()),
                            algorithm=hashes.SHA256(),
                            label=None
                        )
                    )
                )
            f = open(fullNewF, 'w')
            for i in range(0, len(decryptedFileList)):
                f.write(decryptedFileList[i].decode())
            f.close()
            shred(fullPath)

标签: pythonpython-3.xencryptioncryptographyencryption-asymmetric

解决方案


readline() 方法无论出于何种原因都不起作用,但 readlines() 可以正常工作。


推荐阅读