Advertisement
Guest User

Extract Hikvision DAV file

a guest
Sep 22nd, 2015
4,734
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. from binascii import hexlify, unhexlify
  2. from itertools import izip, cycle
  3. import struct
  4. from sys import argv
  5.  
  6. filename = argv[1]
  7.  
  8. with open(filename,'rb') as fware:
  9.     header_structure = '<iiiiii'
  10.     header = fware.read(struct.calcsize(header_structure))
  11.    
  12.     short_key = unhexlify('BACDBCFED6CADDD3BAB9A3ABBFCBB5BE')
  13.  
  14.     # The longer key just rotates the short_key left by 1 byte each time
  15.     key = ''
  16.     for i in range(0,16):
  17.         key += short_key
  18.         short_key = short_key[1:16] + short_key[0]
  19.  
  20.     # XOR decode the header
  21.     header = ''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in izip(header, cycle(key)))
  22.    
  23.     magic_number, header_checksum, total_length, file_number, language, device_class = struct.unpack_from(header_structure, header, 0)
  24.  
  25.     print ('Magic number:    %08x' % magic_number)
  26.     print ('Header checksum: %08x' % header_checksum)
  27.     print ('Header length:   %08x' % total_length)
  28.     print ('File number:     %08x' % file_number)
  29.     print ('Language:        %08x' % language)
  30.     print ('Device class:    %08x' % device_class)
  31.  
  32.     fware.seek(0)
  33.     header = fware.read(total_length)
  34.  
  35.     header = ''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in izip(header, cycle(key)))
  36.  
  37.     # Header checksum is just a byte sum from the checksum to length
  38.     print ('Calced checksum: %08x' % sum(ord(b) for b in header[12:]))
  39.  
  40.     # Extract the filenames and locations in the file.
  41.     index = 64
  42.     for _ in range(0, file_number):
  43.         file_structure = '32siii'
  44.         file_structure_size = struct.calcsize(file_structure)
  45.  
  46.         print hexlify(header[index:index+file_structure_size])
  47.         file_name, file_start, file_length,checksum = struct.unpack_from('32siii', header, index)
  48.  
  49.         file_name = file_name.strip('\0')
  50.         print ('File name:          %s' % file_name)
  51.         print ('Start:              %08x' % file_start)
  52.         print ('Length:             %08x' % file_length)
  53.         print ('Checksum:           %08x' % checksum)
  54.  
  55.         index += file_structure_size
  56.  
  57.         fware.seek(file_start)
  58.  
  59.         file = fware.read(file_length)
  60.  
  61.         print ('Calced checksum:    %08x' % sum(ord(b) for b in file))
  62.  
  63.         with open(file_name,'wb') as outfile:
  64.             outfile.write(file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement