def identities(cert):
    """
    RFC2818: "If a subjectAltName extension of type dNSName is present,
    that MUST be used as the identity."

    >>> identities({
    ...     "subject": ((("commonName", "a"),),),
    ...     "subjectAltName": (("DNS", "x"),)
    ... })
    ['x']

    RFC2818: "Otherwise, the (most specific) Common Name field in the
    Subject field of the certificate MUST be used."

    >>> identities({
    ...     "subject": ((("commonName", "a"), ("commonName", "a.b")),)
    ... })
    ['a.b']

    RFC2818: "If more than one identity of a given type is present in
    the certificate (e.g., more than one dNSName name, a match in any one
    of the set is considered acceptable.)"

    >>> sorted(identities({
    ...     "subjectAltName": (("DNS", "x"), ("DNS", "x.y"))
    ... }))
    ['x', 'x.y']
    """

    alt_name = cert.get("subjectAltName", ())
    dns_names = [value for (key, value) in alt_name if key == "DNS"]
    if dns_names:
        return dns_names

    common_names = list()
    for fields in cert.get("subject", ()):
        common_names.extend(value for (key, value) in fields if key == "commonName")
    if common_names:
        return common_names[-1:]

    return []