Python calculate checksum
24 Python code examples are found related to "
calculate checksum".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: ip_advertisement.py From octavia with Apache License 2.0 | 9 votes |
def calculate_icmpv6_checksum(packet): """Calculate the ICMPv6 checksum for a packet. :param packet: The packet bytes to checksum. :returns: The checksum integer. """ total = 0 # Add up 16-bit words num_words = len(packet) // 2 for chunk in unpack("!%sH" % num_words, packet[0:num_words * 2]): total += chunk # Add any left over byte if len(packet) % 2: total += packet[-1] << 8 # Fold 32-bits into 16-bits total = (total >> 16) + (total & 0xffff) total += total >> 16 return ~total + 0x10000 & 0xffff
Example 2
Source File: ipv6.py From pyspinel with Apache License 2.0 | 9 votes |
def calculate_checksum(self): saved_checksum = self.upper_layer_protocol.checksum self.upper_layer_protocol.checksum = 0 upper_layer_protocol_bytes = self.upper_layer_protocol.to_bytes() self.upper_layer_protocol.checksum = saved_checksum pseudo_header = IPv6PseudoHeader(self.ipv6_header.source_address, self.ipv6_header.destination_address, len(upper_layer_protocol_bytes), self.upper_layer_protocol.type) return calculate_checksum(pseudo_header.to_bytes() + upper_layer_protocol_bytes)
Example 3
Source File: ICMP6.py From cracke-dit with MIT License | 8 votes |
def calculate_checksum(self): #Initialize the checksum value to 0 to yield a correct calculation self.set_checksum(0) #Fetch the pseudo header from the IP6 parent packet pseudo_header = self.parent().get_pseudo_header() #Fetch the ICMP data icmp_header = self.get_bytes() #Build an array of bytes concatenating the pseudo_header, the ICMP header and the ICMP data (if present) checksum_array = array.array('B') checksum_array.extend(pseudo_header) checksum_array.extend(icmp_header) if (self.child()): checksum_array.extend(self.child().get_bytes()) #Compute the checksum over that array self.set_checksum(self.compute_checksum(checksum_array))
Example 4
Source File: ean.py From viivakoodi with MIT License | 8 votes |
def calculate_checksum(self): """Calculates the checksum for EAN13-Code. :returns: The checksum for `self.ean`. :rtype: Integer """ def sum_(x, y): return int(x) + int(y) evensum = reduce(sum_, self.ean[::2]) oddsum = reduce(sum_, self.ean[1::2]) return (10 - (((evensum * 3) + oddsum) % 10)) % 10 # Shortcuts
Example 5
Source File: barcode.py From Trusty-cogs with MIT License | 8 votes |
def calculate_checksum(self): check = sum([MAP[x][0] for x in self.code]) % 43 for k, v in MAP.items(): if check == v[0]: return k
Example 6
Source File: crypto.py From cashaddress with MIT License | 7 votes |
def calculate_checksum(prefix, payload): poly = polymod(prefix_expand(prefix) + payload + [0, 0, 0, 0, 0, 0, 0, 0]) out = list() for i in range(8): out.append((poly >> 5 * (7 - i)) & 0x1f) return out
Example 7
Source File: humble_hash.py From hb-downloader with MIT License | 7 votes |
def calculate_checksum(full_filename): """ Calculates the MD5 checksum for the given file and returns the hex representation. :param full_filename: The full path and filename of the file to calculate the MD5 for. :return: The hex representation of the MD5 hash. :rtype: str """ if full_filename is None or not os.path.exists(full_filename): return "" current_percentage = 0 with open(full_filename, "rb") as f: total_length = os.path.getsize(full_filename) read_bytes = 0 Events.trigger(Events.EVENT_MD5_START, full_filename) md5_hash = hashlib.md5() while True: data = f.read(HumbleHash.chunk_size) read_bytes += HumbleHash.chunk_size read_bytes = min(total_length, read_bytes) if not data: break md5_hash.update(data) current_percentage = Events.check_percent(read_bytes, total_length, current_percentage) Events.trigger(Events.EVENT_MD5_END, full_filename) HumbleHash.write_md5file(full_filename, md5_hash.hexdigest()) return md5_hash.hexdigest()
Example 8
Source File: baumer.py From compas_fab with MIT License | 7 votes |
def calculate_checksum(self, command): """Checks that message is complete.""" code_points = [ord(c) for c in list(command)] checksum = 0 for i in code_points: checksum = checksum ^ i return str(checksum).zfill(3)
Example 9
Source File: history.py From ci_edit with Apache License 2.0 | 7 votes |
def calculateChecksum(filePath, data=None): """ Calculates the hash value of the specified file. The second argument can be passed in if a file's data has already been read so that you do not have to read the file again. Args: filePath (str): The absolute path to the file. data (str): Defaults to None. This is the data returned by calling read() on a file object. Returns: The hash value of the file's data. """ app.log.info("Calculate checksum of the current file") hasher = hashlib.sha512() try: if data is not None: if len(data) == 0: return None hasher.update(data.encode(u"utf-8")) else: with open(filePath, 'rb') as dataFile: data = dataFile.read() if len(data) == 0: return None hasher.update(data) return hasher.hexdigest() except FileNotFoundError as e: pass except Exception as e: app.log.exception(e) return None
Example 10
Source File: ChecksumLabel.py From urh with GNU General Public License v3.0 | 7 votes |
def calculate_checksum_for_message(self, message, use_decoded_bits: bool) -> array.array: data = array.array("B", []) bits = message.decoded_bits if use_decoded_bits else message.plain_bits for data_range in self.data_ranges: data.extend(bits[data_range[0]:data_range[1]]) return self.calculate_checksum(data)
Example 11
Source File: intel.py From microparse with GNU General Public License v2.0 | 7 votes |
def calculate_extended_table_checksum(self): if self.is_extended: checksum = self.extended_signature_count + self.unknown4 + self.unknown5 + self.unknown6 for s in self.extended_processor_signature: checksum += s for s in self.extended_processor_flags: checksum += s for s in self.extended_checksums: checksum += s return -checksum & 0xFFFFFFFF
Example 12
Source File: intel.py From microparse with GNU General Public License v2.0 | 7 votes |
def calculate_checksum(self): checksum = self.header_version + self.update_revision + self.date + self.processor_signature + self.loader_revision + self.processor_flags + self.data_size + self.total_size + self.unknown1 + self.unknown2 + self.unknown3 for v in self.data: checksum += v return -checksum & 0xFFFFFFFF
Example 13
Source File: intel.py From microparse with GNU General Public License v2.0 | 7 votes |
def calculate_extended_signature_checksum(self, offset): if self.is_extended: checksum = calculate_checksum() - self.processor_flags - self.processor_signature + self.extended_processor_signature[offset] + self.extended_processor_flags[offset] return -checksum & 0xFFFFFFFF
Example 14
Source File: utils.py From regipy with MIT License | 7 votes |
def calculate_xor32_checksum(b: bytes) -> int: """ Calculate xor32 checksum from buffer :param b: buffer :return: The calculated checksum """ checksum = 0 if len(b) % 4 != 0: raise RegipyGeneralException(f'Buffer must be multiples of four, {len(b)} length buffer given') for i in range(0, len(b), 4): checksum = (b[i] + (b[i + 1] << 0x08) + (b[i + 2] << 0x10) + (b[i + 3] << 0x18)) ^ checksum return checksum
Example 15
Source File: adb_protocol.py From python-adb with Apache License 2.0 | 7 votes |
def CalculateChecksum(data): # The checksum is just a sum of all the bytes. I swear. if isinstance(data, bytearray): total = sum(data) elif isinstance(data, bytes): if data and isinstance(data[0], bytes): # Python 2 bytes (str) index as single-character strings. total = sum(map(ord, data)) else: # Python 3 bytes index as numbers (and PY2 empty strings sum() to 0) total = sum(data) else: # Unicode strings (should never see?) total = sum(map(ord, data)) return total & 0xFFFFFFFF
Example 16
Source File: esptool.py From EspBuddy with GNU General Public License v3.0 | 7 votes |
def calculate_checksum(self): """ Calculate checksum of loaded image, based on segments in segment array. """ checksum = ESPLoader.ESP_CHECKSUM_MAGIC for seg in self.segments: if seg.include_in_checksum: checksum = ESPLoader.checksum(seg.data, checksum) return checksum
Example 17
Source File: icmp.py From tensor with MIT License | 7 votes |
def calculateChecksum(self, buffer): nleft = len(buffer) sum = 0 pos = 0 while nleft > 1: sum = ord(buffer[pos]) * 256 + (ord(buffer[pos + 1]) + sum) pos = pos + 2 nleft = nleft - 2 if nleft == 1: sum = sum + ord(buffer[pos]) * 256 sum = (sum >> 16) + (sum & 0xFFFF) sum += (sum >> 16) sum = (~sum & 0xFFFF) return sum
Example 18
Source File: common.py From pai with Eclipse Public License 2.0 | 7 votes |
def calculate_checksum(message): r = 0 for c in message: r += c r = (r % 256) return bytes([r])
Example 19
Source File: lib_utils.py From glusto-tests with GNU General Public License v3.0 | 7 votes |
def calculate_checksum(mnode, file_list, chksum_type='sha256sum'): """This module calculates given checksum for the given file list Example: calculate_checksum("abc.com", [file1, file2]) Args: mnode (str): Node on which cmd has to be executed. file_list (list): absolute file names for which checksum to be calculated Kwargs: chksum_type (str): type of the checksum algorithm. Defaults to sha256sum Returns: NoneType: None if command execution fails, parse errors. dict: checksum value for each file in the given file list """ cmd = chksum_type + " %s" % ' '.join(file_list) ret = g.run(mnode, cmd) if ret[0] != 0: g.log.error("Failed to execute checksum command in server %s" % mnode) return None checksum_dict = {} for line in ret[1].split('\n')[:-1]: match = re.search(r'^(\S+)\s+(\S+)', line.strip()) if match is None: g.log.error("checksum output is not in expected format") return None checksum_dict[match.group(2)] = match.group(1) return checksum_dict