简体   繁体   English

将 PEM 文件转换为 DER

[英]Convert PEM file to DER

I am currently trying to write a script that allows me to compute the Tor HS address from the hiddens service's private key file.我目前正在尝试编写一个脚本,允许我从隐藏服务的私钥文件中计算 Tor HS 地址。 In order to do this the file needs to be brought into the DER format.为此,需要将文件转换为 DER 格式。

Using OpenSSL this can be done with:使用 OpenSSL,这可以通过以下方式完成:

openssl rsa -in private_key -pubout -outform DER

Piping this into python with:将其通过管道传输到 python 中:

base64.b32encode(hashlib.sha1(sys.stdin.read()[22:]).digest()[:10]).lower()'

will return the address correctly.将正确返回地址。

However I would like to perform the same using only python.但是我想只使用 python 执行相同的操作。 My problem is that using the pycrypto module the DER output is different and the address therefore incorrect.我的问题是使用 pycrypto 模块,DER 输出不同,因此地址不正确。

key = RSA.importKey(keyfile.read()).publickey()
print(key.exportKey(format='DER'))

Will result in a different output than the openssl call.将导致与 openssl 调用不同的输出。 Is this just a matter of implementation that allows different results?这只是一个允许不同结果的实施问题吗? Or am I making a mistake somewhere?还是我在某个地方犯了错误?

Any help would be appreciated任何帮助,将不胜感激

convert certificate to der using python使用python将证书转换为der

first we load the file首先我们加载文件

cert_file = keyfile.read()

Then we convert it to pem format然后我们把它转换成pem格式

from OpenSSL import crypto
cert_pem = crypto.load_certificate(crypto.FILETYPE_PEM, cert_file)

now we are generating the der-output现在我们正在生成der-output
ie: output equals to openssl x509 -outform der -in certificate.pem -out certificate.der.即: output equals to openssl x509 -outform der -in certificate.pem -out certificate.der.

cert_der = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert_pem)

I was looking for something similar and, as of March 2019, OpenSSL recommends using pyca/cryptography instead of the crypto module.我一直在寻找类似的东西,截至 2019 年 3 月,OpenSSL 建议使用pyca/cryptography而不是crypto模块。 ( source ) 来源

Here after is then what you intend to do: convert PEM to DER接下来是您打算执行的操作:将 PEM 转换为 DER

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

with open("id_rsa", "rb") as keyfile:
    # Load the PEM format key
    pemkey = serialization.load_pem_private_key(
        keyfile.read(),
        None,
        default_backend()
    )
    # Serialize it to DER format
    derkey = pemkey.private_bytes(
        serialization.Encoding.DER,
        serialization.PrivateFormat.TraditionalOpenSSL,
        serialization.NoEncryption()
    )
    # And write the DER format to a file
    with open("key.der", "wb") as outfile:
        outfile.write(derkey)

I want Convert Certificate file not the key file from DER to PEM, but Google took me here.我想要转换证书文件而不是从 DER 到 PEM 的密钥文件,但谷歌把我带到了这里。 thanks @alleen1's answer, I can convert certificate or key from DER to PEM and vice versa.感谢@ alleen1 的回答,我可以将证书或密钥从 DER 转换为 PEM,反之亦然。

Step one , load the file.第一步,加载文件。

Step two ,save it to the format you want.第二步,保存为你想要的格式。

I ommit the process to get the "pem_data" and "der_data",you can get it from file or anywhere else.我省略了获取“pem_data”和“der_data”的过程,您可以从文件或其他任何地方获取它。 they should be bytes not string, use method .encode() when needed.它们应该是字节而不是字符串,需要时使用方法 .encode()。

from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend

# Step one, load the file. 

# Load key file
# PEM 
key = serialization.load_pem_private_key(pem_data, None, default_backend())
# DER
key = serialization.load_pem_private_key(der_data, None, default_backend())

# Load cert file
# PEM
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
# DER
cert = x509.load_der_x509_certificate(der_data, default_backend())

# Step two,save it to the format you want.
# PEM key
key_val = key.private_bytes(
              serialization.Encoding.PEM,
              serialization.PrivateFormat.TraditionalOpenSSL,
              serialization.NoEncryption()
          )
# DER key
key_val = key.private_bytes(
              serialization.Encoding.DER,
              serialization.PrivateFormat.TraditionalOpenSSL,
              serialization.NoEncryption()
          )

# PEM cert
cert_val = cert.public_bytes(serialization.Encoding.PEM)
# DER cert
cert_val = cert.public_bytes(serialization.Encoding.DER)

The inital question is: " Exact the public key from private key ", this because the openSSL command states "pubout" in initial question.最初的问题是:“从私钥精确获取公钥”,这是因为 openSSL 命令在最初的问题中声明了“pubout”。

Using OpenSSL this can be done with: (note that "pubout" defines OUTPUT as public key only)使用 OpenSSL,这可以通过以下方式完成:(请注意,“pubout”仅将 OUTPUT 定义为公钥)

openssl ALGORITHM_USED -in private_key -pubout -outform DER

But with Python cryptography module you can exact the public key from private key (note this seems applicable for RSA and EC based cryptography).但是使用 Python 加密模块,您可以从私钥中提取公钥(注意这似乎适用于基于 RSA 和 EC 的加密)。

With Python:使用 Python:

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

    # Create private key (example uses elliptic curve encryption)

    priv_key = ec.generate_private_key(ec.SECP256K1, default_backend())

    pub_key = priv_key.public_key()

    pub_key_pem = pub_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

    with open('public_key.pem', 'wb') as outfile:
        outfile.write(public_key_pem)

More info on cryptography documentation: https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/#cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey有关密码学文档的更多信息: https : //cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/#cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM