如何使用 pyopenssl 解密 RSA 加密文件(通过 PHP 和 OpenSSL)?

How to decrypt RSA encrypted file (via PHP and OpenSSL) with pyopenssl?

简单的 n00b 问题:我正在尝试复制 openssl_private_decrypt function in PHP to decrypt a file that a vendor is sending me which was encrypted via the openssl_public_encrypt function. I am using python 3.4 and thus the only library I can see available is pyopenssl 的行为,但它的级别太低,我无法轻易找到如何做我想做的事情。这可能很简单,但是有人有我想做的事的例子吗?

使用 Cryptography module,您可以安装:

$ pip install cryptography

假设您将私钥存储在名为 "path/to/key.pem" 的文件中,首先加载私钥:

from cryptography.hazmat.primitives import serialization 
with open("path/to/key.pem", "rb") as key_file: 
    private_key = serialization.load_pem_private_key(
        key_file.read(),
        password=None,
        backend=default_backend() 
    )

然后你解密:

plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None
    )
)

多亏了@mnistic,它才开始工作,尽管有一些修改。这是最终的工作代码(你必须记住 openssl_private_decrypt 的默认值):

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding

# It's critical that the file be opened in mode "rb"!
with open("private.key", 'rb') as key_file:
  private_key = serialization.load_pem_private_key(key_file.read(), password=None, backend=default_backend())

with open('encrypted_file', 'rb') as encrypted_file:
  ciphertext = encrypted_file.read()

plaintext = private_key.decrypt(ciphertext, padding.PKCS1v15())

请注意 ciphertext 需要小于密钥的最大块大小(对于 RSA,这是密钥中的位数除以 8)。希望对未来的 Google 员工有所帮助!