如何使用Python、密钥及密码短语解密Azure Blob中的PGP文件
解密Azure存储资源管理器Blob中PGP加密ZIP文件的Python方案
先解决路径转义错误
你遇到的'unicodeescape' codec can't decode bytes in position 2-3错误,是Windows路径中的反斜杠\被Python识别为转义字符导致的,三种解决方式任选其一:
- 使用原始字符串:在路径前加
r,例如r"C:\Files\encrypted.pgp" - 替换反斜杠为双反斜杠:
"C:\\Files\\encrypted.pgp" - 用正斜杠替代反斜杠:
"C:/Files/encrypted.pgp"
完整解密流程(含Blob文件获取)
1. 安装依赖包
先安装所需的Python库:
pip install pgpy azure-storage-blob
2. 完整代码实现
import pgpy import zipfile from azure.storage.blob import BlobServiceClient # 1. 从Azure Blob下载加密的PGP文件 azure_conn_str = "你的Azure存储账户连接字符串" container_name = "Blob容器名称" blob_file_name = "目标PGP加密文件名(如data.pgp)" local_pgp_file = "本地临时存储PGP文件的路径" # 初始化Blob客户端并下载文件 blob_service = BlobServiceClient.from_connection_string(azure_conn_str) blob_client = blob_service.get_blob_client(container=container_name, blob=blob_file_name) with open(local_pgp_file, "wb") as f: f.write(blob_client.download_blob().read()) # 2. 解密PGP文件 # 加载私钥并解锁 private_key, _ = pgpy.PGPKey.from_file(r"你的私钥文件路径") with private_key.unlock("你的私钥密码短语"): encrypted_msg = pgpy.PGPMessage.from_file(local_pgp_file) # 解密得到ZIP格式的字节数据 decrypted_zip_data = private_key.decrypt(encrypted_msg).message # 3. 解压解密后的ZIP文件 temp_zip_path = "临时保存ZIP文件的路径" extract_target_dir = "ZIP文件解压目标文件夹" # 写入ZIP文件并解压 with open(temp_zip_path, "wb") as f: f.write(decrypted_zip_data) with zipfile.ZipFile(temp_zip_path, 'r') as zip_ref: zip_ref.extractall(extract_target_dir) print(f"文件已成功解压至:{extract_target_dir}")
注意事项
- 确保Azure存储账户连接字符串正确,且拥有目标Blob的读取权限
- 私钥文件路径同样需要规避转义问题,建议使用原始字符串格式
- 若不需要本地临时文件,可直接在内存中处理PGP消息与ZIP数据,减少磁盘IO操作
内容的提问来源于stack exchange,提问作者PeterP
相关产品推荐
相关产品推荐

