【问题标题】:Encrypting private key in Python在 Python 中加密私钥
【发布时间】:2019-07-29 16:02:18
【问题描述】:

我有一个 DER 格式的私钥。我正在尝试将其转换为 PEM 并同时使用密码加密私钥。

这是我用来转换和加密的 openssl 命令:

> openssl rsa -aes256 -inform der -in temp_key.der -outform pem -passout pass:<password>

我正在尝试在 Python 中实现类似的逻辑,其中我有 DER 格式的内存中密钥的数据。 我想将其更改为 PEM,对其进行加密,然后存储到文件中。

我不太熟悉 Python 的 Crypto 库,而且我很难找出正确的方法来转换和加密我的关键数据。

【问题讨论】:

    标签: python openssl pyopenssl python-cryptography


    【解决方案1】:

    您可以在cryptography 模块的帮助下加载 DER 密钥并将其转储为受密码保护的 PEM 密钥,如下所示:

    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.hazmat.primitives import serialization
    
    private_key = serialization.load_der_private_key(
        der_data, # assuming that "der_data" variable contains your DER key
        password=None,
        backend=default_backend()
    )
    
    pem_encrypted = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword')
    )
    
    print(pem_encrypted.decode()) # -----BEGIN ENCRYPTED PRIVATE KEY-----...
    

    【讨论】:

    • 感谢您的回复。我到达了相同的代码。在下面的答案中查看我的实现。
    【解决方案2】:

    其他两个答案都对您有用。纯粹为了品种,我会添加我的。 对于 RSA,我个人更喜欢使用PyCryptodome,因为它在 RSA 密码方面有更多的功能,而且它的 RSA 实例是用纯 Python 编写的。

    这段代码应该适合你:

    from Crypto.PublicKey import RSA
    
    key = RSA.import(open('key.der', 'rb').read())
    
    with open('key.pem', 'wb') as f:
    
        pem_key = key.export_key(passphrase='password')
    
        f.write(pem_key)
        f.close()
    

    如果您愿意,您可以指定导出密钥的输出格式,但 PyCryptodome 目前默认为 PEM。

    您可以分别在 https://cryptography.iohttps://pycryptodome.readthedocs.io 找到这两个库的完整文档。

    【讨论】:

    • 我认为在第二行代码中你想写 RSA.import_key
    【解决方案3】:

    在 python 中使用了cryptography 模块 这是我达到的实现

    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.hazmat.primitives.serialization import load_der_private_key
    from cryptography.hazmat.primitives import serialization
    
    
    key = load_der_private_key(
                der_data, password=None, backend=default_backend())
    
    password_protected_key = key.private_bytes(encoding=serialization.Encoding.PEM,
                                            format=serialization.PrivateFormat.TraditionalOpenSSL,
                                            encryption_algorithm=serialization.BestAvailableEncryption("password"))
    

    【讨论】:

    • 如果此答案有效,请将其添加为选定答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 2011-03-20
    • 2011-04-18
    • 2013-04-06
    • 2011-08-14
    • 1970-01-01
    相关资源
    最近更新 更多