uuid.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (c) 2003-2016 CORE Security Technologies
  2. #
  3. # This software is provided under under a slightly modified version
  4. # of the Apache Software License. See the accompanying LICENSE file
  5. # for more information.
  6. #
  7. # Description:
  8. # Generate UUID compliant with http://www.webdav.org/specs/draft-leach-uuids-guids-01.txt.
  9. # A different, much simpler (not necessarily better) algorithm is used.
  10. #
  11. # Author:
  12. # Javier Kohen (jkohen)
  13. #
  14. import re
  15. from random import randrange
  16. from struct import pack, unpack
  17. def generate():
  18. # UHm... crappy Python has an maximum integer of 2**31-1.
  19. top = (1L<<31)-1
  20. return pack("IIII", randrange(top), randrange(top), randrange(top), randrange(top))
  21. def bin_to_string(uuid):
  22. uuid1, uuid2, uuid3 = unpack('<LHH', uuid[:8])
  23. uuid4, uuid5, uuid6 = unpack('>HHL', uuid[8:16])
  24. return '%08X-%04X-%04X-%04X-%04X%08X' % (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6)
  25. def string_to_bin(uuid):
  26. matches = re.match('([\dA-Fa-f]{8})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})([\dA-Fa-f]{8})', uuid)
  27. (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = map(lambda x: long(x, 16), matches.groups())
  28. uuid = pack('<LHH', uuid1, uuid2, uuid3)
  29. uuid += pack('>HHL', uuid4, uuid5, uuid6)
  30. return uuid
  31. def stringver_to_bin(s):
  32. (maj,min) = s.split('.')
  33. return pack('<H',int(maj)) + pack('<H',int(min))
  34. def uuidtup_to_bin(tup):
  35. if len(tup) != 2: return
  36. return string_to_bin(tup[0]) + stringver_to_bin(tup[1])
  37. def bin_to_uuidtup(bin):
  38. assert len(bin) == 20
  39. uuidstr = bin_to_string(bin[:16])
  40. maj, min = unpack("<HH", bin[16:])
  41. return uuidstr, "%d.%d" % (maj, min)
  42. #input: string
  43. #output: tuple (uuid,version)
  44. #if version is not found in the input string "1.0" is returned
  45. #example:
  46. # "00000000-0000-0000-0000-000000000000 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0')
  47. # "10000000-2000-3000-4000-500000000000 version 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0')
  48. # "10000000-2000-3000-4000-500000000000 v 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0')
  49. # "10000000-2000-3000-4000-500000000000" returns ('00000000-0000-0000-0000-000000000000','1.0')
  50. def string_to_uuidtup(s):
  51. g = re.search("([A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}).*?([0-9]{1,5}\.[0-9]{1,5})",s+" 1.0")
  52. if g:
  53. (u,v) = g.groups()
  54. return (u,v)
  55. return
  56. def uuidtup_to_string(tup):
  57. uuid, (maj, min) = tup
  58. return "%s v%d.%d" % (uuid, maj, min)