这是家庭作业! 我使用
get_peer_certificate()
获取服务器的证书
并调用 dump_certificate
将证书转储到变量中。格式是 PEM,看起来很适合我。
-----BEGIN CERTIFICATE-----
GIBBERISH................
......................
........................
-----END CERTIFICATE-----
如何从该文件('server.pubkey')中提取服务器的公钥并使用
plaintext
算法和任何 python 库加密 RSA
。在撰写本文时,我正在使用 pyOpenSSL
我建议使用更广泛的加密库,例如 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)
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)
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()
请注意,OpenSSL 库 不建议用于这些目的。相反,密码学库是指向的。它得到维护并定期更新。
假设您有 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)