Beispiel #1
0
def check_file(opt):
    """
    Calculate the CRC of a file.
    This algorithm uses the table_driven CRC algorithm.
    """
    if opt.UndefinedCrcParameters:
        sys.stderr.write("%s: error: undefined parameters\n" % sys.argv[0])
        sys.exit(1)
    alg = Crc(width = opt.Width, poly = opt.Poly,
        reflect_in = opt.ReflectIn, xor_in = opt.XorIn,
        reflect_out = opt.ReflectOut, xor_out = opt.XorOut,
        table_idx_width = opt.TableIdxWidth)

    try:
        in_file = open(opt.CheckFile, 'rb')
    except IOError:
        sys.stderr.write("%s: error: can't open file %s\n" % (sys.argv[0], opt.CheckFile))
        sys.exit(1)

    if not opt.ReflectIn:
        register = opt.XorIn
    else:
        register = alg.reflect(opt.XorIn, opt.Width)
    # Read bytes from the file.
    check_byte_str = in_file.read()
    while check_byte_str:
        register = crc_file_update(alg, register, check_byte_str)
        check_byte_str = in_file.read()
    in_file.close()

    if opt.ReflectOut:
        register = alg.reflect(register, opt.Width)
    register = register ^ opt.XorOut
    return register
Beispiel #2
0
 def __get_table_init(self):
     """
     Return the precalculated CRC table for the table_driven implementation.
     """
     if self.opt.Algorithm != self.opt.Algo_Table_Driven:
         return "0"
     if self.opt.Width == None or self.opt.Poly == None or self.opt.ReflectIn == None:
         return "0"
     crc = Crc(
         width=self.opt.Width,
         poly=self.opt.Poly,
         reflect_in=self.opt.ReflectIn,
         xor_in=0,
         reflect_out=False,
         xor_out=0,  # set unimportant variables to known values
         table_idx_width=self.opt.TableIdxWidth)
     tbl = crc.gen_table()
     if self.opt.Width >= 32:
         values_per_line = 4
     elif self.opt.Width >= 16:
         values_per_line = 8
     else:
         values_per_line = 16
     format_width = max(self.opt.Width, 8)
     out = ""
     for i in range(self.opt.TableWidth):
         if i % values_per_line == 0:
             out += "    "
         if i == (self.opt.TableWidth - 1):
             out += "%s" % self.__pretty_hex(tbl[i], format_width)
         elif i % values_per_line == (values_per_line - 1):
             out += "%s,\n" % self.__pretty_hex(tbl[i], format_width)
         else:
             out += "%s, " % self.__pretty_hex(tbl[i], format_width)
     return out
def maxim_ibutton_crc(data):
    crc = Crc(width=8,
              poly=0x31,
              reflect_in=True,
              xor_in=0x00,
              reflect_out=True,
              xor_out=0x00)
    return crc.bit_by_bit(data)
Beispiel #4
0
def _get_init_value(opt):
    """
    Return the init value of a C implementation, according to the selected
    algorithm and to the given options.
    If no default option is given for a given parameter, value in the cfg_t
    structure must be used.
    """
    if opt.algorithm == opt.algo_bit_by_bit:
        if opt.xor_in is None or opt.width is None or opt.poly is None:
            return None
        crc = Crc(width=opt.width,
                  poly=opt.poly,
                  reflect_in=opt.reflect_in,
                  xor_in=opt.xor_in,
                  reflect_out=opt.reflect_out,
                  xor_out=opt.xor_out,
                  table_idx_width=opt.tbl_idx_width)
        init = crc.nondirect_init
    elif opt.algorithm == opt.algo_bit_by_bit_fast:
        if opt.xor_in is None:
            return None
        init = opt.xor_in
    elif opt.algorithm == opt.algo_table_driven:
        if opt.reflect_in is None or opt.xor_in is None or opt.width is None:
            return None
        if opt.poly is None:
            poly = 0
        else:
            poly = opt.poly
        crc = Crc(width=opt.width,
                  poly=poly,
                  reflect_in=opt.reflect_in,
                  xor_in=opt.xor_in,
                  reflect_out=opt.reflect_out,
                  xor_out=opt.xor_out,
                  table_idx_width=opt.tbl_idx_width)
        if opt.reflect_in:
            init = crc.reflect(crc.direct_init, opt.width)
        else:
            init = crc.direct_init
    else:
        init = 0
    return _pretty_hex(init, opt.width)
Beispiel #5
0
 def __get_init_value(self):
     """
     Return the init value of a C implementation, according to the selected algorithm and
     to the given options.
     If no default option is given for a given parameter, value in the cfg_t structure must be used.
     """
     if self.opt.Algorithm == self.opt.Algo_Bit_by_Bit:
         if self.opt.XorIn == None or self.opt.Width == None or self.opt.Poly == None:
             return None
         crc = Crc(width=self.opt.Width,
                   poly=self.opt.Poly,
                   reflect_in=self.opt.ReflectIn,
                   xor_in=self.opt.XorIn,
                   reflect_out=self.opt.ReflectOut,
                   xor_out=self.opt.XorOut,
                   table_idx_width=self.opt.TableIdxWidth)
         init = crc.NonDirectInit
     elif self.opt.Algorithm == self.opt.Algo_Bit_by_Bit_Fast:
         if self.opt.XorIn == None:
             return None
         init = self.opt.XorIn
     elif self.opt.Algorithm == self.opt.Algo_Table_Driven:
         if self.opt.ReflectIn == None or self.opt.XorIn == None or self.opt.Width == None:
             return None
         if self.opt.Poly == None:
             poly = 0
         else:
             poly = self.opt.Poly
         crc = Crc(width=self.opt.Width,
                   poly=poly,
                   reflect_in=self.opt.ReflectIn,
                   xor_in=self.opt.XorIn,
                   reflect_out=self.opt.ReflectOut,
                   xor_out=self.opt.XorOut,
                   table_idx_width=self.opt.TableIdxWidth)
         if self.opt.ReflectIn:
             init = crc.reflect(crc.DirectInit, self.opt.Width)
         else:
             init = crc.DirectInit
     else:
         init = 0
     return self.__pretty_hex(init, self.opt.Width)
Beispiel #6
0
    class Helper(object):
        CRC = Crc(
            width=16,
            poly=0x8005,
            reflect_in=False,
            xor_in=0xFFFF,
            reflect_out=False,
            xor_out=0x0000
        )  # specification is slightly unclear, figured out by trial-and-error

        @staticmethod
        def unitTest():
            assert ESSPDevice.Helper.crc([0x80, 0x01, 0x01]) == [0x06, 0x02]
            assert ESSPDevice.Helper.crc([0x80, 0x01, 0xF0]) == [0x23, 0x80]

        @classmethod
        def splitBytes(cls, uint16):
            # uint16 -> [lowByte, highByte]
            return [uint16 & 0xFF, uint16 >> 8]

        @classmethod
        def crc(cls, data):
            c = cls.CRC.bit_by_bit(data)
            return cls.splitBytes(c)

        @classmethod
        def Unsigned32ToBytes(cls, x):
            # return little-endian representation
            return ESSPDevice.Helper.UnsignedToBytes(x, n=4)

        @staticmethod
        def Unsigned64ToBytes(x):
            # return little-endian representation
            return ESSPDevice.Helper.UnsignedToBytes(x, n=8)

        @staticmethod
        def UnsignedToBytes(x, n):
            r = []
            for _ in range(n):
                r.append(x & 0xFF)
                x = x >> 8
            return r

        @classmethod
        def AsciiToBytes(cls, x):
            return [ord(c) for c in x]

        @staticmethod
        def byteArrayToString(data):
            return b''.join([chr(x) for x in data])

        @staticmethod
        def stringToByteArray(string):
            return ([ord(x) for x in string])
Beispiel #7
0
def check_string(opt):
    """
    Return the calculated CRC sum of a string.
    """
    error = False
    if opt.undefined_crc_parameters:
        sys.stderr.write("{0:s}: error: undefined parameters\n".format(
            sys.argv[0]))
        sys.exit(1)
    if opt.algorithm == 0:
        opt.algorithm = opt.algo_bit_by_bit | opt.algo_bit_by_bit_fast | opt.algo_table_driven

    alg = Crc(width=opt.width,
              poly=opt.poly,
              reflect_in=opt.reflect_in,
              xor_in=opt.xor_in,
              reflect_out=opt.reflect_out,
              xor_out=opt.xor_out,
              table_idx_width=opt.tbl_idx_width)

    crc = None
    if opt.algorithm & opt.algo_bit_by_bit:
        bbb_crc = alg.bit_by_bit(opt.check_string)
        if crc != None and bbb_crc != crc:
            error = True
        crc = bbb_crc
    if opt.algorithm & opt.algo_bit_by_bit_fast:
        bbf_crc = alg.bit_by_bit_fast(opt.check_string)
        if crc != None and bbf_crc != crc:
            error = True
        crc = bbf_crc
    if opt.algorithm & opt.algo_table_driven:
        # no point making the python implementation slower by using less than 8 bits as index.
        opt.tbl_idx_width = 8
        tbl_crc = alg.table_driven(opt.check_string)
        if crc != None and tbl_crc != crc:
            error = True
        crc = tbl_crc

    if error:
        sys.stderr.write("{0:s}: error: different checksums!\n".format(
            sys.argv[0]))
        if opt.algorithm & opt.algo_bit_by_bit:
            sys.stderr.write(
                "       bit-by-bit:        {0:#x}\n".format(bbb_crc))
        if opt.algorithm & opt.algo_bit_by_bit_fast:
            sys.stderr.write(
                "       bit-by-bit-fast:   {0:#x}\n".format(bbf_crc))
        if opt.algorithm & opt.algo_table_driven:
            sys.stderr.write(
                "       table_driven:      {0:#x}\n".format(tbl_crc))
        sys.exit(1)
    return crc
Beispiel #8
0
def calc_crc(data):
    crc = Crc(width=16,
              poly=0x8005,
              reflect_in=True,
              xor_in=0xffff,
              reflect_out=True,
              xor_out=0x0000)

    my_crc = crc.bit_by_bit_fast(data)
    lsb = my_crc & 0b0000000011111111
    msb = (my_crc & 0b1111111100000000) >> 8
    return [lsb, msb]
Beispiel #9
0
 def __init__(self, slaveAddy, functionCode, registerAddy, numRegisters):
     self.slaveAddy = slaveAddy
     self.functionCode = functionCode
     self.registerAddy = registerAddy
     self.numRegisters = numRegisters
     self.crc = Crc(width=16,
                    poly=0x8005,
                    reflect_in=True,
                    xor_in=0xFFFF,
                    reflect_out=True,
                    xor_out=0x0000)
     self.rplyBytes = 0
     self.rplyData = list()  # list of 16 bit integer data
Beispiel #10
0
def check_string(opt):
    """
    Return the calculated CRC sum of a string.
    """
    error = False
    if opt.UndefinedCrcParameters:
        sys.stderr.write("%s: error: undefined parameters\n" % sys.argv[0])
        sys.exit(1)
    if opt.Algorithm == 0:
        opt.Algorithm = opt.Algo_Bit_by_Bit | opt.Algo_Bit_by_Bit_Fast | opt.Algo_Table_Driven

    alg = Crc(width=opt.Width,
              poly=opt.Poly,
              reflect_in=opt.ReflectIn,
              xor_in=opt.XorIn,
              reflect_out=opt.ReflectOut,
              xor_out=opt.XorOut,
              table_idx_width=opt.TableIdxWidth)

    crc = None
    if opt.Algorithm & opt.Algo_Bit_by_Bit:
        bbb_crc = alg.bit_by_bit(opt.CheckString)
        if crc != None and bbb_crc != crc:
            error = True
        crc = bbb_crc
    if opt.Algorithm & opt.Algo_Bit_by_Bit_Fast:
        bbf_crc = alg.bit_by_bit_fast(opt.CheckString)
        if crc != None and bbf_crc != crc:
            error = True
        crc = bbf_crc
    if opt.Algorithm & opt.Algo_Table_Driven:
        # no point making the python implementation slower by using less than 8 bits as index.
        opt.TableIdxWidth = 8
        tbl_crc = alg.table_driven(opt.CheckString)
        if crc != None and tbl_crc != crc:
            error = True
        crc = tbl_crc

    if error:
        sys.stderr.write("%s: error: different checksums!\n" % sys.argv[0])
        if opt.Algorithm & opt.Algo_Bit_by_Bit:
            sys.stderr.write("       bit-by-bit:        0x%x\n" % bbb_crc)
        if opt.Algorithm & opt.Algo_Bit_by_Bit_Fast:
            sys.stderr.write("       bit-by-bit-fast:   0x%x\n" % bbf_crc)
        if opt.Algorithm & opt.Algo_Table_Driven:
            sys.stderr.write("       table_driven:      0x%x\n" % tbl_crc)
        sys.exit(1)
    return crc
Beispiel #11
0
    def __get_crc(self, model, check_str='123456789', expected_crc=None):
        """
        Get the CRC for a set of parameters from the Python reference implementation.
        """
        if self.verbose:
            out_str = 'Crc(width = {width:d}, poly = {poly:#x}, reflect_in = {reflect_in}, xor_in = {xor_in:#x}, reflect_out = {reflect_out}, xor_out = {xor_out:#x})'.format(
                **model)
            if expected_crc is not None:
                out_str += ' [check = {0:#x}]'.format(expected_crc)
            print(out_str)
        alg = Crc(width=model['width'],
                  poly=model['poly'],
                  reflect_in=model['reflect_in'],
                  xor_in=model['xor_in'],
                  reflect_out=model['reflect_out'],
                  xor_out=model['xor_out'])
        error = False
        crc = expected_crc

        if self.use_algo_bit_by_bit:
            bbb_crc = alg.bit_by_bit(check_str)
            if crc is None:
                crc = bbb_crc
            error = error or bbb_crc != crc
        if self.use_algo_bit_by_bit_fast:
            bbf_crc = alg.bit_by_bit_fast(check_str)
            if crc is None:
                crc = bbf_crc
            error = error or bbf_crc != crc
        if self.use_algo_table_driven:
            tbl_crc = alg.table_driven(check_str)
            if crc is None:
                crc = tbl_crc
            error = error or tbl_crc != crc

        if error:
            print('error: different checksums!')
            if expected_crc is not None:
                print('       check:             {0:#x}'.format(expected_crc))
            if self.use_algo_bit_by_bit:
                print('       bit-by-bit:        {0:#x}'.format(bbb_crc))
            if self.use_algo_bit_by_bit_fast:
                print('       bit-by-bit-fast:   {0:#x}'.format(bbf_crc))
            if self.use_algo_table_driven:
                print('       table_driven:      {0:#x}'.format(tbl_crc))
            return None
        return crc
Beispiel #12
0
    def __get_crc(self, model, check_str="123456789", expected_crc=None):
        """
        Get the CRC for a set of parameters from the Python reference implementation.
        """
        if self.verbose:
            out_str = "Crc(width = %(width)d, poly = 0x%(poly)x, reflect_in = %(reflect_in)s, xor_in = 0x%(xor_in)x, reflect_out = %(reflect_out)s, xor_out = 0x%(xor_out)x)" % model
            if expected_crc is not None:
                out_str += " [check = 0x%x]" % expected_crc
            print(out_str)
        alg = Crc(width=model["width"],
                  poly=model["poly"],
                  reflect_in=model["reflect_in"],
                  xor_in=model["xor_in"],
                  reflect_out=model["reflect_out"],
                  xor_out=model["xor_out"])
        error = False
        crc = expected_crc

        if self.use_algo_bit_by_bit:
            bbb_crc = alg.bit_by_bit(check_str)
            if crc is None:
                crc = bbb_crc
            error = error or bbb_crc != crc
        if self.use_algo_bit_by_bit_fast:
            bbf_crc = alg.bit_by_bit_fast(check_str)
            if crc is None:
                crc = bbf_crc
            error = error or bbf_crc != crc
        if self.use_algo_table_driven:
            tbl_crc = alg.table_driven(check_str)
            if crc is None:
                crc = tbl_crc
            error = error or tbl_crc != crc

        if error:
            print("error: different checksums!")
            if expected_crc is not None:
                print("       check:             0x%x" % expected_crc)
            if self.use_algo_bit_by_bit:
                print("       bit-by-bit:        0x%x" % bbb_crc)
            if self.use_algo_bit_by_bit_fast:
                print("       bit-by-bit-fast:   0x%x" % bbf_crc)
            if self.use_algo_table_driven:
                print("       table_driven:      0x%x" % tbl_crc)
            return None
        return crc
Beispiel #13
0
def _get_table_init(opt):  # TODO: change to return a list
    """
    Return the precalculated CRC table for the table_driven implementation.
    """
    if opt.algorithm != opt.algo_table_driven:
        return "0"
    if opt.width is None or opt.poly is None or opt.reflect_in is None:
        return "0"
    crc = Crc(
        width=opt.width,
        poly=opt.poly,
        reflect_in=opt.reflect_in,
        xor_in=0,
        reflect_out=False,
        xor_out=0,  # set unimportant variables to known values
        table_idx_width=opt.tbl_idx_width,
        slice_by=opt.slice_by)
    crc_tbl = crc.gen_table()
    if opt.width > 32:
        values_per_line = 4
    elif opt.width >= 16:
        values_per_line = 8
    else:
        values_per_line = 16
    format_width = max(opt.width, 8)
    if opt.slice_by == 1:
        indent = 4
    else:
        indent = 8

    out = [''] * opt.slice_by
    for i in range(opt.slice_by):
        out[i] = _get_simple_table(opt, crc_tbl[i], values_per_line,
                                   format_width, indent)
    fixed_indent = ' ' * (indent - 4)
    out = '{0:s}{{\n'.format(fixed_indent) + \
        '\n{0:s}}},\n{0:s}{{\n'.format(fixed_indent).join(out) + \
        '\n{0:s}}}'.format(fixed_indent)
    if opt.slice_by == 1:
        return out
    return '{\n' + out + '\n}'
Beispiel #14
0
 def __get_crc_bwe_bitmask_minterms(self):
     """
     Return a list of (bitmask, minterms), for all bits.
     """
     crc = Crc(width = self.opt.Width, poly = self.opt.Poly,
             reflect_in = self.opt.ReflectIn, xor_in = self.opt.XorIn,
             reflect_out = self.opt.ReflectOut, xor_out = self.opt.XorOut,
             table_idx_width = self.opt.TableIdxWidth)
     qm = QuineMcCluskey(use_xor = True)
     crc_tbl = crc.gen_table()
     bm_mt = []
     for bit in range(max(self.opt.Width, 8)):
         ones = [i for i in range(self.opt.TableWidth) if crc_tbl[i] & (1 << bit) != 0]
         terms = qm.simplify(ones, [])
         if self.opt.Verbose:
             print("bit %02d: %s" % (bit, terms))
         if terms != None:
             for term in terms:
                 shifted_term = '.' * bit + term + '.' * (self.opt.Width - bit - 1)
                 bm_mt.append((1 << bit, shifted_term))
     return bm_mt
def check_file(opt):
    """
    Calculate the CRC of a file.
    This algorithm uses the table_driven CRC algorithm.
    """
    if opt.undefined_crc_parameters:
        sys.stderr.write("{0:s}: error: undefined parameters\n".format(
            sys.argv[0]))
        sys.exit(1)
    alg = Crc(width=opt.width,
              poly=opt.poly,
              reflect_in=opt.reflect_in,
              xor_in=opt.xor_in,
              reflect_out=opt.reflect_out,
              xor_out=opt.xor_out,
              table_idx_width=opt.tbl_idx_width)

    try:
        in_file = open(opt.check_file, 'rb')
    except IOError:
        sys.stderr.write("{0:s}: error: can't open file {1:s}\n".format(
            sys.argv[0], opt.check_file))
        sys.exit(1)

    if not opt.reflect_in:
        register = opt.xor_in
    else:
        register = alg.reflect(opt.xor_in, opt.width)
    # Read bytes from the file.
    check_bytes = in_file.read(1024)
    while check_bytes:
        register = crc_file_update(alg, register, check_bytes)
        check_bytes = in_file.read(1024)
    in_file.close()

    if opt.reflect_out:
        register = alg.reflect(register, opt.width)
    register = register ^ opt.xor_out
    return register
Beispiel #16
0
        0xee00, 0x0000, 0x0080, 0xfe7f, 0x0000, 0x8900, 0x8900, 0x550d, 0x0601,
        0x0601, 0x2200, 0x5500, 0xab1a, 0xca08, 0x6400, 0x6400, 0x9001, 0x2823
    ]
]
crcs = [0xC0F8, 0x72F8, 0x95EE]
initialValue = 0x3132

# 4e00ffff26ec14091600a018303931323031313131303039303031323031303030303131313030393030313230313030303031313130303930303132303130303030ffff225e343331324f313537
# 6400000000000000808080808080000000000000
# e001eb00130105000e010500bc029001900190013c00280046002800a816681040012b001e004f000200bb0080018000330100c0000599990100000033b3cd4c00600601ae070a575c0fc3b5d7634a0f1f8548a1b81e5c8f333300c0f6286009aec7852b5238cd4c3200b80b3700d801880422018002e80334000032890100000000cd664801830048013d0a040114006400c201bbfe3c0071027e010f00dc0500003403dc05cd4c33339a19dc052400b81e7b1466e6a4f0ffffdb034821d703a410f6280000480166e66f126f1271fd71fde7f30040250000000000000000005e80a27fb89e856bd5010004660285034200200024053200640032001900f40129180000080001002602a0000a00c800320028000a001400fa035613821428000002000096009600d007000027005000b004540014006400fa00220be2045e016400dc05800c28000a000500140573007300e1031c00ee0000000080fe7f000089008900550d0601060122005500ab1aca086400640090012823

from crc_algorithms import Crc

crcer = Crc(width=16,
            poly=0xaabd,
            reflect_in=False,
            xor_in=initialValue,
            reflect_out=False,
            xor_out=0xd706)
print("0x%x" % crcer.bit_by_bit(datas[0]))
print("0x%x" % crcer.bit_by_bit(datas[1]))
print("0x%x" % crcer.bit_by_bit(datas[2]))

for data, crc in zip(datas, crcs):
    print("Looking for checksum of 0x%x in 0x%x bytes..." %
          (crc, len(data) * 2))
    for poly in range(0x0000, 0xFFFF):
        crcer = Crc(width=16,
                    poly=poly,
                    reflect_in=False,
                    xor_in=initialValue,
                    reflect_out=False,
#   See the License for the specific language governing permissions and
#   limitations under the License.
import serial
import struct
import math
import sys
from crc_algorithms import Crc
import serial
import StringIO

slvAddy = int(sys.argv[1])
boardNum = int(sys.argv[2])

crc = Crc(width=8,
          poly=0x8005,
          reflect_in=True,
          xor_in=0xFFFF,
          reflect_out=True,
          xor_out=0x0000)

# for slvAddy in range(63):
if True:
    # slvAddy = 0x01
    # boardNum = 0x08

    ser = serial.Serial(port="/dev/ttyUSB0",
                        parity=serial.PARITY_NONE,
                        baudrate=9600,
                        stopbits=serial.STOPBITS_ONE,
                        timeout=30)
    # ser.open()
    print "poopy1"
Beispiel #18
0
import collections

import datetime

from packet_definitions import *
from crc_algorithms import Crc
from cryptograph import *
from keystore import *

crc = Crc(width=16,
          poly=0x1021,
          reflect_in=True,
          xor_in=0xffff,
          reflect_out=False,
          xor_out=0x0000)


def pretty_parsed(x):
    print pretty_parsed_string(x)


def pretty_parsed_string(x):
    if x is None: return
    result = ''
    if (x['status'] == "identified"):
        result += pretty_string(x['records'])
    else:
        result += x['reason'] + "\n"
    if ('valid' in x):
        result += "         valid:  " + str(x['valid'])
    return result