酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

使用非对称加密算法RSA对我桌面上的txt文档进行加密解密

下面是使用Python实现使用RSA非对称加密算法对桌面上的txt文档进行加密和解密的代码: ```python from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import os # 生成RSA密钥对 def generate_rsa_keys(): key = RSA.generate(2048) private_key = key.export_key() public_key = key.publickey().export_key() # 将私钥保存到文件 with open('private.pem', 'wb') as f: f.write(private_key) # 将公钥保存到文件 with open('public.pem', 'wb') as f: f.write(public_key) return private_key, public_key # 加密文件 def encrypt_file(file_path, public_key_path): # 读取公钥 with open(public_key_path, 'rb') as f: public_key = RSA.import_key(f.read()) cipher = PKCS1_OAEP.new(public_key) # 读取文件内容 with open(file_path, 'rb') as f: data = f.read() # 由于RSA加密有长度限制,这里分块加密 chunk_size = 200 encrypted_chunks = [] for i in range(0, len(data), chunk_size): chunk = data[i:i+chunk_size] encrypted_chunk = cipher.encrypt(chunk) encrypted_chunks.append(encrypted_chunk) encrypted_data = b''.join(encrypted_chunks) # 将加密后的数据保存到新文件 encrypted_file_path = file_path + '.encrypted' with open(encrypted_file_path, 'wb') as f: f.write(encrypted_data) return encrypted_file_path # 解密文件 def decrypt_file(encrypted_file_path, private_key_path): # 读取私钥 with open(private_key_path, 'rb') as f: private_key = RSA.import_key(f.read()) cipher = PKCS1_OAEP.new(private_key) # 读取加密文件内容 with open(encrypted_file_path, 'rb') as f: encrypted_data = f.read() # 分块解密 chunk_size = 256 decrypted_chunks = [] for i in range(0, len(encrypted_data), chunk_size): chunk = encrypted_data[i:i+chunk_size] decrypted_chunk = cipher.decrypt(chunk) decrypted_chunks.append(decrypted_chunk) decrypted_data = b''.join(decrypted_chunks) # 去掉文件名中的.encrypted后缀 original_file_path = encrypted_file_path.replace('.encrypted', '') # 将解密后的数据保存到原文件 with open(original_file_path, 'wb') as f: f.write(decrypted_data) return original_file_path # 主函数 if __name__ == "__main__": # 获取桌面路径 desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") file_path = os.path.join(desktop_path, "example.txt") # 生成密钥对 generate_rsa_keys() public_key_path = 'public.pem' private_key_path = 'private.pem' # 加密文件 encrypted_file_path = encrypt_file(file_path, public_key_path) print(f"文件已加密,加密后的文件路径: {encrypted_file_path}") # 解密文件 decrypted_file_path = decrypt_file(encrypted_file_path, private_key_path) print(f"文件已解密,解密后的文件路径: {decrypted_file_path}") ``` 额外注意的逻辑点 1. RSA加密有长度限制,加密时需要分块处理,分块大小要根据密钥长度合理设置。 2. 私钥的安全性非常重要,要妥善保管,避免泄露,否则加密的数据可能会被他人解密。 3. 加密和解密使用的密钥必须是一对,即公钥加密的数据只能用对应的私钥解密。 [2025-06-30 19:55:05 | AI写代码神器 | 929点数解答]

相关提问