minor int_to_bytes performance increase (#3490)
* minor int_to_bytes performance increase
* why is Python 2.6 supported anyway...
* keep py2k version
diff --git a/src/cryptography/utils.py b/src/cryptography/utils.py
index ab3c84e..6d30485 100644
--- a/src/cryptography/utils.py
+++ b/src/cryptography/utils.py
@@ -51,13 +51,19 @@
return int(bytes(data).encode('hex'), 16)
-def int_to_bytes(integer, length=None):
- hex_string = '%x' % integer
- if length is None:
- n = len(hex_string)
- else:
- n = length * 2
- return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
+if hasattr(int, "to_bytes"):
+ def int_to_bytes(integer, length=None):
+ return integer.to_bytes(
+ length or (integer.bit_length() + 7) // 8 or 1, 'big'
+ )
+else:
+ def int_to_bytes(integer, length=None):
+ hex_string = '%x' % integer
+ if length is None:
+ n = len(hex_string)
+ else:
+ n = length * 2
+ return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
class InterfaceNotImplemented(Exception):