python给文件加密_python可以破解软件吗

python给文件加密_python可以激活成功教程软件吗在 Python 中加密文件可以通过多种方法实现 以下是使用 cryptography 库进行 AES 加密的示例代码 pythonfrom cryptography fernet import Fernet def encrypt file file path key 读取文件内容 with open file path rb as file file content

在Python中加密文件可以通过多种方法实现,以下是使用`cryptography`库进行AES加密的示例代码:

python

from cryptography.fernet import Fernet

def encrypt_file(file_path, key):

读取文件内容

with open(file_path, 'rb') as file:

file_content = file.read()

创建加密器

cipher = Fernet(key)

加密文件内容

encrypted_content = cipher.encrypt(file_content)

将加密后的内容写入新文件

encrypted_file_path = file_path + '.enc'

with open(encrypted_file_path, 'wb') as encrypted_file:

encrypted_file.write(encrypted_content)

示例用法

file_path = 'path/to/file.txt'

key = Fernet.generate_key() 生成密钥

encrypt_file(file_path, key)

如果你需要加密整个目录,可以使用以下代码:

python

import os

import hashlib

def encrypt_directory(directory, password):

for root, dirs, files in os.walk(directory):

for file in files:

path = os.path.join(root, file)

with open(path, 'rb') as f:

data = f.read()

key = hashlib.sha256(password.encode()).hexdigest()

encrypted_data = bytearray(x ^ ord(key[i % len(key)]) for i, x in enumerate(data))

with open(path, 'wb') as f:

f.write(encrypted_data)

示例用法

directory_path = 'path/to/directory'

password = input('Enter a password: ')

encrypt_directory(directory_path, password)

请注意,上述代码示例使用了`cryptography`库,该库需要安装。你可以使用`pip`来安装:

pip install cryptography

如果你需要更高级的加密方法,比如非对称加密,可以使用`cryptography`库中的其他函数,例如RSA加密。

请根据你的具体需求选择合适的加密算法和库,并确保密钥的安全管理

编程小号
上一篇 2025-05-07 19:21
下一篇 2026-04-16 10:04

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/56715.html