import struct


def keytag(dnskey):
    """
    Given a dns.rdtypes.ANY.DNSKEY, compute and return its keytag.
    
    See rfc2535 section 4.1.6 for details.
    """
    if dnskey.algorithm == 1:
        a = ord(dnskey.key[-3]) << 8
        b = ord(dnskey.key[-2])
        return a + b
    else:
        header = struct.pack("!HBB", dnskey.flags, dnskey.protocol,
                                dnskey.algorithm)
        key = header + dnskey.key
        ac = 0
        for i, value in enumerate(ord(x) for x in key):
            if i % 2:
                ac += value
            else:
                ac += (value << 8)
        ac += (ac >> 16) & 0xffff
        return ac & 0xffff