- import copy
- import zlib
-
-
- # https://github.com/Michaelangel007/crc32
- def crc8():
- test_crc8 = 0x11 # 数据
- poly_crc8 = 0x11d # 多项式
- for bit in range(8):
- if (test_crc8 & 0x80) != 0: # 判断首位是否为1
- test_crc8 <<= 1 # 右移
- test_crc8 ^= poly_crc8 # 异或计算
- else:
- test_crc8 <<= 1 # 不等于1则直接移位
- print(hex(test_crc8))
-
-
- crc8()
-
- def crc32():
- test_crc32 = 0x01
- test_crc32 <<= 24
- poly_crc32_1 = 0xedb88320
- poly_crc32_2 = 0x104c11db7
- for bit in range(8):
- if (test_crc32 & 0x80000000) != 0: # 判断首位是否为1
- test_crc32 <<= 1 # 右移
- test_crc32 ^= poly_crc32_1 # 异或计算
- else:
- test_crc32 <<= 1 # 不等于1则直接移位
- print(hex(test_crc32))
-
-
- def crc32_table_normal(): # 彩虹表算法,查表算法
- crc32_table_normal_list = []
- poly_crc32_normal = 0x104c11db7
- for byte in range(256):
- operator = copy.copy(byte)
- operator <<= 24
- for bit in range(8):
- if (operator & 0x80000000) != 0:
- operator <<= 1
- operator ^= poly_crc32_normal
- else:
- operator <<= 1
- crc32_table_normal_list.append(operator)
- to_print = list(map(hex, crc32_table_normal_list))
- print(to_print)
-
-
- def crc32_table_recip():
- crc32_table_recip_list = []
- poly_crc32_recip = 0x104c11db7
- for byte in range(256):
- operator = copy.copy(byte)
- operator = int('{:08b}'.format(operator)[::-1], 2) # 倒置
- operator <<= 24
- for bit in range(8):
- if (operator & 0x80000000) != 0:
- operator <<= 1
- operator ^= poly_crc32_recip
- else:
- operator <<= 1
- operator = int('{:032b}'.format(operator)[::-1], 2) # 倒置
- crc32_table_recip_list.append(operator)
- to_print = list(map(hex, crc32_table_recip_list))
- print(to_print)
-
- def crc32_recip(line):
- var = 0xffffffff
- for ch in line:
- operator = ord(ch)
- operator = (operator ^ var) & 0xff
- var = crc32_table_recip[operator] ^ (var >> 8)
- return var ^ 0xffffffff
-
-
- # print(hex(zlib.crc32('123456789'.encode('utf-8'))))
- # print(hex(crc32_recip('123456789')))
-
-
- def crc32_normal(line):
- var = 0xffffffff
- for ch in line:
- operator = ord(ch)
- operator = int('{:08b}'.format(operator)[::-1], 2)
- var = crc32_table_normal[operator]^(var << 8)& 0xffffffff
- var = int('{:032b}'.format(operator)[::-1], 2)
- return var ^ 0xffffffff
-
-
- # print(hex(crc32_normal('123456789')))
-
-
- def crc32_table_polyrev():
- crc32_table_polyrev_list = []
- poly_rev = 0xedb88320
- for byte in range(256):
- operator = copy.copy(byte)
- for bit in range(8):
- if (operator & 0x1) != 0:
- operator >>= 1
- operator^=poly_rev
- else:
- operator >>= 1
- crc32_table_polyrev_list.append(operator)
- to_print_polyrev = list(map(hex, crc32_table_polyrev_list))
- print(to_print_polyrev)
-
-
-
- # crc逆算法
- def crc8_reverse():
- test_crc32_result = 0xd0
- poly_crc32 = 0x11d
- for bit in range(8):
- if test_crc32_result & 1 == 1:
- test_crc32_result ^= poly_crc32
- test_crc32_result <<= 1
- test_crc32_result |= 0x80
- continue
- else:
- test_crc32_result <<= 1
- print(hex(test_crc32_result & 0x08))
-
-
- crc32_reverse()