要安全地解密和移动文件,可以使用以下解决方法:
下面是一个使用Python的PyCryptodome库进行文件加密和解密的示例代码:
from Cryptodome.Cipher import AES
import os
def encrypt_file(key, filepath, output_path):
cipher = AES.new(key, AES.MODE_EAX)
with open(filepath, 'rb') as file:
plaintext = file.read()
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
with open(output_path, 'wb') as file:
[file.write(x) for x in (cipher.nonce, tag, ciphertext)]
def decrypt_file(key, encrypted_path, output_path):
with open(encrypted_path, 'rb') as file:
nonce, tag, ciphertext = [file.read(x) for x in (16, 16, -1)]
cipher = AES.new(key, AES.MODE_EAX, nonce)
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
with open(output_path, 'wb') as file:
file.write(plaintext)
# 生成一个随机的16字节密钥
key = os.urandom(16)
# 加密文件
encrypt_file(key, 'file.txt', 'encrypted_file.bin')
# 解密文件
decrypt_file(key, 'encrypted_file.bin', 'decrypted_file.txt')
下面是一个使用Python的cryptography库进行公钥加密和私钥解密的示例代码:
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
# 生成公钥和私钥
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# 保存公钥和私钥到文件
with open('private_key.pem', 'wb') as file:
file.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
with open('public_key.pem', 'wb') as file:
file.write(public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
))
# 加载公钥和私钥
with open('private_key.pem', 'rb') as file:
private_key = serialization.load_pem_private_key(
file.read(),
password=None
)
with open('public_key.pem', 'rb') as file:
public_key = serialization.load_pem_public_key(
file.read()
)
# 使用公钥加密密钥
key = b'my_secret_key'
encrypted_key = public_key.encrypt(
key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# 使用私钥解密密钥
decrypted_key = private_key.decrypt(
encrypted_key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# 使用解密后的密钥进行文件解密
decrypt_file(decrypted_key, 'encrypted_file.bin', 'decrypted_file.txt')
通过以上方法,您可以安全地解密和移动文件,并确保只有授权的人可以访问文件内容。确保妥善保管私钥,以免泄露密钥和文件内容。
上一篇:安全地解包空元组数组
下一篇:安全地解析嵌套的JSON双引号