uuid.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. try:
  18. long # Python 2
  19. except NameError:
  20. long = int # Python 3
  21. def generate():
  22. # UHm... crappy Python has an maximum integer of 2**31-1.
  23. top = (1<<31)-1
  24. return pack("IIII", randrange(top), randrange(top), randrange(top), randrange(top))
  25. def bin_to_string(uuid):
  26. uuid1, uuid2, uuid3 = unpack('<LHH', uuid[:8])
  27. uuid4, uuid5, uuid6 = unpack('>HHL', uuid[8:16])
  28. return '%08X-%04X-%04X-%04X-%04X%08X' % (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6)
  29. def string_to_bin(uuid):
  30. 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)
  31. (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = map(lambda x: long(x, 16), matches.groups())
  32. uuid = pack('<LHH', uuid1, uuid2, uuid3)
  33. uuid += pack('>HHL', uuid4, uuid5, uuid6)
  34. return uuid
  35. def stringver_to_bin(s):
  36. (maj,min) = s.split('.')
  37. return pack('<H',int(maj)) + pack('<H',int(min))
  38. def uuidtup_to_bin(tup):
  39. if len(tup) != 2: return
  40. return string_to_bin(tup[0]) + stringver_to_bin(tup[1])
  41. def bin_to_uuidtup(bin):
  42. assert len(bin) == 20
  43. uuidstr = bin_to_string(bin[:16])
  44. maj, min = unpack("<HH", bin[16:])
  45. return uuidstr, "%d.%d" % (maj, min)
  46. #input: string
  47. #output: tuple (uuid,version)
  48. #if version is not found in the input string "1.0" is returned
  49. #example:
  50. # "00000000-0000-0000-0000-000000000000 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0')
  51. # "10000000-2000-3000-4000-500000000000 version 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0')
  52. # "10000000-2000-3000-4000-500000000000 v 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0')
  53. # "10000000-2000-3000-4000-500000000000" returns ('00000000-0000-0000-0000-000000000000','1.0')
  54. def string_to_uuidtup(s):
  55. 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")
  56. if g:
  57. (u,v) = g.groups()
  58. return (u,v)
  59. return
  60. def uuidtup_to_string(tup):
  61. uuid, (maj, min) = tup
  62. return "%s v%d.%d" % (uuid, maj, min)