aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/cryptography/utils.py20
1 files changed, 13 insertions, 7 deletions
diff --git a/src/cryptography/utils.py b/src/cryptography/utils.py
index ab3c84e1..6d304856 100644
--- a/src/cryptography/utils.py
+++ b/src/cryptography/utils.py
@@ -51,13 +51,19 @@ else:
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):