使用GNUPG在Databricks中实现文件加解密遇阻求助
我通过在线工具生成RSA 4096位PGP密钥,在Databricks中编写加解密函数并存储密钥,但加密操作始终失败。以下是相关代码、错误日志及解决方法:
加密代码
import gnupg import os gpg = gnupg.GPG(gnupghome='pgp_keys/') def encrypt_file(file_path, output_path): with open(file_path, 'rb') as f: encrypted_data = gpg.encrypt_file(f, "a@xyz.com") with open(output_path, 'wb') as encrypted_file: encrypted_file.write(encrypted_data.data) print('ok: ', encrypted_data.ok) print('status: ', encrypted_data.status) print('stderr: ', encrypted_data.stderr)
加密错误日志
ok: False status: invalid recipient stderr: gpg: WARNING: unsafe permissions on homedir '/Workspace/Users/a@xyz.com/pgp_keys' [GNUPG:] KEY_CONSIDERED 337B0001AEB11E875CBFE01C99E7824740791203 0 [GNUPG:] KEY_CONSIDERED 337B0001AEB11E875CBFE01C99E7824740791203 0 gpg: 01E18C0B5E758C10: There is no assurance this key belongs to the named user [GNUPG:] INV_RECP 10 a@xyz.com [GNUPG:] FAILURE encrypt 53 gpg: [stdin]: encryption failed: Unusable public key
解密代码
def decrypt_file(file_path, output_path): with open(file_path, 'rb') as f: decrypted_data = gpg.decrypt_file(f,passphrase='passphrase', output=output_path) return decrypted_data.ok
解决步骤
1. 修复PGP目录权限
GnuPG要求密钥目录权限必须为700(仅所有者可读写执行),Databricks默认目录权限可能不符合要求,执行以下代码修改:
# 针对Workspace路径 dbutils.fs.chmod("/Workspace/Users/a@xyz.com/pgp_keys", "700") # 若为本地路径,使用os模块 import os os.chmod('/Workspace/Users/a@xyz.com/pgp_keys', 0o700)
2. 标记公钥为信任状态
GnuPG默认不信任未验证的密钥,需手动设置信任级别:
# 导入公钥(若未导入) with open('pgp_keys/public_key.asc', 'r') as f: import_result = gpg.import_keys(f.read()) # 将密钥标记为完全信任 gpg.trust_keys(import_result.fingerprints[0], 'TRUST_ULTIMATE')
3. 确认密钥正确导入
检查密钥是否成功导入到指定目录:
# 列出所有已导入密钥 keys = gpg.list_keys() for key in keys: print(f"密钥ID: {key['keyid']}, 用户ID: {key['uids']}")
确保输出中包含a@xyz.com对应的密钥,若未显示则重新导入公钥文件。
4. 加密时使用密钥ID而非邮箱
避免邮箱关联多个密钥导致的识别问题,直接使用密钥ID加密:
# 替换为日志中显示的密钥ID(如337B0001AEB11E875CBFE01C99E7824740791203) encrypted_data = gpg.encrypt_file(f, "337B0001AEB11E875CBFE01C99E7824740791203")
5. 优化解密函数的错误排查
为解密函数添加日志输出,便于定位问题:
def decrypt_file(file_path, output_path): with open(file_path, 'rb') as f: decrypted_data = gpg.decrypt_file(f, passphrase='passphrase', output=output_path) print('解密状态: ', decrypted_data.ok) print('解密详情: ', decrypted_data.status) print('错误日志: ', decrypted_data.stderr) return decrypted_data.ok
内容的提问来源于stack exchange,提问作者Ajay

