python 从证书中提取公钥并加密数据

ldioqlga  于 2023-01-16  发布在  Python
关注(0)|答案(4)|浏览(281)

这是一个家庭作业!我使用get_peer_certificate()获取服务器的证书,并调用dump_certificate将证书转储到一个变量中。格式是PEM,看起来很正确。

-----BEGIN CERTIFICATE-----
GIBBERISH................
......................
........................

-----END CERTIFICATE-----

如何从这个文件('server. pubkey')中提取服务器的公钥,并使用RSA算法和任何python库加密plaintext

q0qdq0h2

q0qdq0h21#

我建议使用更广泛的crypto library such as M2Crypto,它具有X509证书功能和RSA加密:

from M2Crypto import RSA, X509
data = ssl_sock.getpeercert(1)
# load the certificate into M2Crypto to manipulate it
cert = X509.load_cert_string(data, X509.FORMAT_DER)
pub_key = cert.get_pubkey()
rsa_key = pub_key.get_rsa()
cipher = rsa_key.public_encrypt('plaintext', RSA.pkcs1_padding)
gmol1639

gmol16392#

from OpenSSL import crypto        
    crtObj = crypto.load_certificate(crypto.FILETYPE_ASN1, config.x509_certificate)
    pubKeyObject = crtObj.get_pubkey()
    pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM, pubKeyObject)
weylhg0b

weylhg0b3#

from cryptography.x509 import load_pem_x509_certificate

cert_str = b"-----BEGIN CERTIFICATE-----MIIDETCCAfm..."
cert_obj = load_pem_x509_certificate(cert_str)
public_key = cert_obj.public_key()
private_key = cert_obj.private_key()

来源:https://pyjwt.readthedocs.io/en/stable/faq.html

toiithl6

toiithl64#

请注意,不建议将OpenSSL library用于这些目的。相反,cryptography library是指向的。它会得到维护和定期更新。
假设您拥有Pem格式的证书,下面的代码块将为您提供字符串形式的公钥。

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

def read_pub_key_from_cert()
    # Read certificate file.
    with open("tls.crt") as certificate:
        cert = certificate.read()

    # Convert it into bytes.
    cert_in_bytes = bytes(cert, 'utf-8')

    # Create x509 certificate object.
    cert_obj = x509.load_pem_x509_certificate(cert_in_bytes)

    # Create Public key object.
    public_key_obj = cert_obj.public_key()

    # Convert Public key object into Pem format in bytes.
    public_pem = public_key_obj.public_bytes(
                    encoding=serialization.Encoding.PEM,
                    format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    # Convert Public key into string.
    pub_key_string = public_pem.decode("utf-8")

    return(pub_key_string)

相关问题