Pick the right client key/certificate to use for the given server and
    return it in the form Twisted wants.

    :param NetLocation netloc: The location of the server to consider.
    :param dict[TLSCredentials] possible: The available credentials from which
        to choose.

    :return: A two-tuple.  If no credentials were found, the elements are
        ``None`` and ``[]``.  Otherwise, the first element is a
        ``twisted.internet.ssl.PrivateCertificate`` instance representing the
        client certificate to use and the second element is a ``tuple`` of
        ``twisted.internet.ssl.Certificate`` instances representing the rest
        of the chain necessary to validate the client certificate.

def pick_cert_for_twisted(netloc, possible):
    """
    Pick the right client key/certificate to use for the given server and
    return it in the form Twisted wants.

    :param NetLocation netloc: The location of the server to consider.
    :param dict[TLSCredentials] possible: The available credentials from which
        to choose.

    :return: A two-tuple.  If no credentials were found, the elements are
        ``None`` and ``[]``.  Otherwise, the first element is a
        ``twisted.internet.ssl.PrivateCertificate`` instance representing the
        client certificate to use and the second element is a ``tuple`` of
        ``twisted.internet.ssl.Certificate`` instances representing the rest
        of the chain necessary to validate the client certificate.
    """
    try:
        creds = possible[netloc]
    except KeyError:
        return (None, ())

    key = ssl.KeyPair.load(creds.key.as_bytes(), FILETYPE_PEM)
    return (
        ssl.PrivateCertificate.load(
            creds.chain.certificates[0].as_bytes(), key, FILETYPE_PEM,
        ),
        tuple(
            ssl.Certificate.load(cert.as_bytes(), FILETYPE_PEM)
            for cert
            in creds.chain.certificates[1:]
        ),
    )