我们有一个旧版 python2 应用程序,它使用 RSA 私钥来解密 Base64 编码的文件。我们如何将其移植到 python3?
def _unlock_keys(self, passphrase):
#get user priv key passphrase and perform unlock of randbits
master_key = None
master_key_path = 'master.pem'
with open(master_key_path) as f:
master_key = RSA.importKey(f.read(), passphrase)
with open('host_keys/part.A') as f:
enc_bits = f.read()
self.part_A = master_key.decrypt(b64decode(enc_bits))
# self.part_A has the data we need
这是我们在 python3 代码上尝试过的方法,但到目前为止它解密为空字节串
b''
:
def _unlock_keys(self, passphrase):
#get user priv key passphrase and perform unlock of randbits
master_key = None
master_key_path = 'master.pem'
with open(master_key_path) as f:
master_key = RSA.importKey(f.read(), passphrase)
with open('host_keys/part.A') as f:
enc_bits = f.read()
# Note: PKCS1_OAEP doesn't work because this is raw, unpadded:
decryptor = PKCS1_v1_5.new(master_key)
self.part_A = decryptor.decrypt(b64decode(enc_bits), "error")
print(self.part_A)
# self.part_A prints as b''
我们可以使用OpenSSL对其进行解密,如下所示。请注意
-raw
参数,因为没有 PKCS 填充,这是 PKCS v1.5:
openssl rsautl -pkcs -raw -decrypt -in <(base64 -d host_keys/part.A) -out /proc/self/fd/1 -inkey master.pem
Enter pass phrase for master.pem:
<correct output>
(也许我应该提出问题“如何在python3中实现这个openssl命令?”但我认为这将是一个XY问题......)
如果有帮助,这就是私钥格式。
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,<REDACTED>
...
-----END RSA PRIVATE KEY-----
哦,我知道这个。我要么使用 rsa 模块,要么使用 openssl 的子进程