#!/usr/bin/env python

def crc16(buff, crc = 0, poly = 0x8408):
    l = len(buff)
    i = 0
    while i < l:
        ch = ord(buff[i])
        uc = 0
        while uc < 8:
            if (crc & 1) ^ (ch & 1):
                crc = (crc >> 1) ^ poly
            else:
                crc >>= 1
            ch >>= 1
            uc += 1
        i += 1
    return crc

p1 = 'a\x88nY3U6\x00\x00\x08\x00U6\x00\x00\x1ez\x01=\x05\x01'
key = 'pCTF_ZigBee_LOL'
p2 = '\x00\x1a[A\x00\x00\xff\x0f\x00\xff\xff\xff\xff\xff\xff\xff\xff'

for i in range(256):
  if crc16(p1 + key + chr(i) + p2)==0xd3a1:
    print "Recovered byte %r (%02x)" % (chr(i),i)
    print "Key is %r (%s)" % (key+chr(i), (key+chr(i)).encode("hex"))

# Recovered byte '\xea' (ea)
# Key is 'pCTF_ZigBee_LOL\xea' (704354465f5a69674265655f4c4f4cea)

# use Perytons to decrypt zigbee packets with this key
# http://evaluation.perytons.com/PerytonsEval_3.22.1183.5918.exe
# scroll and find flag z1gb33_r0ck5
