正在 Python 中加密私钥

Encrypting private key in Python

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

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

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

我正在尝试在 Python 中实现类似的逻辑,其中我有 DER 格式的内存中密钥数据。 我想把它改成PEM,加密后存到文件里。

我不太熟悉 Python 的加密库,我很难找到转换和加密我的密钥数据的正确方法。

您可以在 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-----...

cryptography 模块用于 python 这是我在

达到的实现
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"))

其他两个答案都适合您。纯粹为了多样性,我将添加我的。 对于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.io and https://pycryptodome.readthedocs.io 找到这两个库的详尽文档。