import base64
import binascii

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519, rsa


def parsedkim(line):

    # remove escaped quote characters, they can break our parser
    line = line.replace('\\"', "")

    qsplit = line.split('"')
    # Concat quoted strings if we have double quotes.
    # Exception: if we have a '=' before the first quote it is not
    # a quoted record, but quotes within a DKIM value (see example
    # in tests/data/dkim/dkim-comment-quotes.txt).
    if len(qsplit) >= 2 and "=" not in qsplit[0]:
        add = 0
        dk = ""
        for x in line.split('"'):
            add ^= 1
            if add == 0:
                dk += x
    else:
        dk = line

    dkim = {}
    for x in dk.split(";"):
        s = x.split("=", 1)
        if len(s) != 2:
            continue
        key = s[0].strip()
        value = s[1].strip()
        dkim[key] = value
    if "p" not in dkim:
        return False
    if dkim["p"] == "":
        return False
    if "k" not in dkim:
        dkim["k"] = "rsa"

    if dkim["k"] == "rsa":
        try:
            rawkey = base64.b64decode(dkim["p"].encode())
        except (binascii.Error, UnicodeEncodeError):
            return "base64error"
        try:
            pubkey = serialization.load_der_public_key(rawkey)
        except ValueError:
            try:
                serialization.load_der_private_key(rawkey, password=None)
                return "privleak"
            except ValueError:
                pass
            return "keyparseerror"
        if not isinstance(pubkey, rsa.RSAPublicKey):
            return "expectedrsa"
        return pubkey
    if dkim["k"] == "ed25519":
        try:
            rawed = base64.b64decode(dkim["p"].encode())
        except (binascii.Error, UnicodeEncodeError):
            return "base64error"
        if len(rawed) != 32:
            return "wrongkeylength"
        return ed25519.Ed25519PublicKey.from_public_bytes(rawed)
    return "unknowntype"
