Skip to main content
 首页 » 编程设计

python之将 PEM 文件转换为 DER

2025年05月04日16pengyingh

我目前正在尝试编写一个脚本,允许我从隐藏服务的私钥文件中计算 Tor HS 地址。 为此,需要将文件转换为 DER 格式。

使用 OpenSSL 这可以通过以下方式完成:

openssl rsa -in private_key -pubout -outform DER 

通过以下方式将其通过管道传输到 python 中:

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

将正确返回地址。

但是我想只使用 python 来执行相同的操作。我的问题是使用 pycrypto 模块 DER 输出不同,因此地址不正确。

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

将产生与 openssl 调用不同的输出。 这只是允许不同结果的实现问题吗?还是我在某处犯了错误?

任何帮助将不胜感激

请您参考如下方法:

使用python将证书转换为der

首先我们加载文件

cert_file = keyfile.read() 

然后我们将其转换为pem格式

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

现在我们正在生成 der-output
即:输出等于 openssl x509 -outform der -in certificate.pem -out certificate.der。

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