_cryptography_backports.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # -*- test-case-name: twisted.conch.test.test_common -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Backported functions from Cryptography to support older versions.
  6. These functions can be obtained from C{cryptography.utils} instead, from
  7. version 1.1 onwards.
  8. """
  9. from __future__ import absolute_import, division
  10. import binascii
  11. import struct
  12. def intFromBytes(data, byteorder, signed=False):
  13. """
  14. Convert an integer in packed form to a Python L{int}.
  15. @type data: L{bytes}
  16. @param data: The packed integer.
  17. @type byteorder: L{str}
  18. @param byteorder: The byte order the data is in. Only C{'big'} is
  19. currently supported.
  20. @type signed: L{bool}
  21. @param signed: C{True} for signed, C{False} for unsigned.
  22. @rtype: L{int}
  23. @return: The decoded integer.
  24. """
  25. assert byteorder == 'big'
  26. assert not signed
  27. if len(data) % 4 != 0:
  28. data = (b'\x00' * (4 - (len(data) % 4))) + data
  29. result = 0
  30. while len(data) > 0:
  31. digit, = struct.unpack('>I', data[:4])
  32. result = (result << 32) + digit
  33. data = data[4:]
  34. return result
  35. def intToBytes(integer, length=None):
  36. """
  37. Convert a Python L{int} to packed data.
  38. @type integer: L{int}
  39. @param integer: The integer to pack.
  40. @type length: L{int} or L{None}
  41. @param length: The length to pad the result to, or L{None} for no padding.
  42. @rtype: L{bytes}
  43. @return: The packed integer.
  44. """
  45. hexString = '%x' % (integer,)
  46. if length is None:
  47. n = len(hexString)
  48. else:
  49. n = length * 2
  50. return binascii.unhexlify(hexString.zfill(n + (n & 1)))