Parses a received packet in to Packet() with corresponding payloads.
        Will decrypt encrypted packets when needed.

        :param data: bytes() IKE packet from wire.
        :return: Packet() instance
        :raise IkeError: on malformed packet

def parse_packet(self, data):
        """
        Parses a received packet in to Packet() with corresponding payloads.
        Will decrypt encrypted packets when needed.

        :param data: bytes() IKE packet from wire.
        :return: Packet() instance
        :raise IkeError: on malformed packet
        """
        packet = Packet(data=data)
        packet.header = data[0:const.IKE_HEADER.size]
        (packet.iSPI, packet.rSPI, next_payload, packet.version, exchange_type, packet.flags,
         packet.message_id, packet.length) = const.IKE_HEADER.unpack(packet.header)
        packet.exchange_type = const.ExchangeType(exchange_type)
        if self.iSPI != packet.iSPI:
            raise IkeError("Initiator SPI mismatch, packet to an unknown IKE SA")
        elif not self.rSPI:
            logger.debug("Setting responder SPI: {0:x}".format(packet.rSPI))
            self.rSPI = packet.rSPI
        elif self.rSPI != packet.rSPI:
            raise IkeError("Responder SPI mismatch, packet to an unknown IKE SA")
        if packet.message_id - int(self.state) != 1:
            logger.debug("message ID {} at state {!r}".format(packet.message_id, self.state))
        logger.debug("next payload: {!r}".format(next_payload))
        if next_payload == 46:
            self.verify_hmac(data)
            next_payload, data = self.decrypt(data[const.IKE_HEADER.size:])
        else:
            data = data[const.IKE_HEADER.size:]
        while next_payload:
            logger.debug('Next payload: {0!r}'.format(next_payload))
            logger.debug('{0} bytes remaining'.format(len(data)))
            try:
                payload = payloads.get_by_type(next_payload)(data=data)
            except KeyError as e:
                logger.error("Unidentified payload {}".format(e))
                payload = payloads._IkePayload(data=data)
            packet.payloads.append(payload)
            logger.debug('Payloads: {0!r}'.format(packet.payloads))
            next_payload = payload.next_payload
            data = data[payload.length:]
        logger.debug("Packed parsed successfully")
        self.packets.append(packet)
        return packet