简体   繁体   English

Python:如何从“ .cert”文件中提取公钥?

[英]Python: How do I extract public key from a '.cert' file?

I have used openssl to generate a X.509 self-signed like so: 我已经使用openssl生成X.509自签名,如下所示:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

This generated two files: cert.pem and a key.pem files. 这生成了两个文件:cert.pem和key.pem文件。

My cert.pem file contains the public key. 我的cert.pem文件包含公用密钥。 How do I extract it using Python? 如何使用Python提取它?
I am unable to use the OpenSSl library of python. 我无法使用python的OpenSSl库。 I am able to use the cryptography library. 我可以使用加密库。
My current code: 我当前的代码:

cert = x509.load_pem_x509_certificate(pem_data, default_backend())
print(cert.public_key)

Unless I'm misunderstanding your question, you'd do it just the same as you would if you were reading any other file's contents with python. 除非我对您的问题有误解,否则您将执行与使用python读取任何其他文件的内容相同的操作。

Something like this should get you started: 这样的事情应该让您入门:

#!/usr/bin/env python

from subprocess import Popen, PIPE, STDOUT
p = Popen(["openssl", "rsa", "-in", "key.pem", "-pubout", "-out", "key.pub"], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
p.stdout.readline().rstrip()

pubkey_file=open('key.pub', 'r')
for line in pubkey_file.readlines():
    data=line.strip('\n')
    print(data)
pubkey_file.close()

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

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