Advertisement
MonroCoury

checksum_calc

Nov 20th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. def bit_not(n, numbits=16):
  5.     return (1 << numbits) - 1 - n
  6.  
  7.  
  8. class ChecksumCalculator:
  9.  
  10.     def __init__(self, tgt):
  11.         self.tgt = tgt
  12.  
  13.     def _conv_16bits(self):
  14.         res_list = []
  15.         temp = "".join(self.tgt.split(" "))
  16.         i = 0
  17.         j = 0
  18.         for x in range(len(temp) // 4):
  19.             unit = ""
  20.             while i < 4:
  21.                 unit += temp[j]
  22.                 i += 1
  23.                 j += 1
  24.             res_list.append(unit)
  25.             i = 0
  26.         return res_list[:-1]
  27.  
  28.     def _calc_sum(self, bits=None):
  29.         s = 0
  30.         if not bits:
  31.             bits=self._conv_16bits()
  32.         for item in bits:
  33.             s += int(item, 16)
  34.  
  35.         res = hex(s).split('x')[-1]
  36.         res = "000" +res[0] + " " + res[1:]
  37.         return res.upper()
  38.  
  39.     def combine_inverse(self):
  40.         s = self._calc_sum().split(" ")
  41.         t = "".join(self._calc_sum(s)[3:].split(" "))
  42.  
  43.         combined = hex(bit_not(int(bin(int(t, 16)), 2))).split('x')[-1].upper()
  44.  
  45.         return " ".join(self._conv_16bits()) + " " + combined
  46.    
  47.  
  48. if __name__ == "__main__":
  49.     pkt_header = input("Please enter a packet header string to process: ").upper()
  50.     job = ChecksumCalculator(pkt_header)
  51.     print("Done! Result is: %s." % job.combine_inverse())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement