[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[tor-commits] [stem/master] Use struct for integer => byte conversions



commit ba630119da869bf65f9c6f8bd8443f3041b7228c
Author: Damian Johnson <atagar@xxxxxxxxxxxxxx>
Date:   Sun Sep 22 17:11:55 2019 -0700

    Use struct for integer => byte conversions
    
    Neat! I didn't realize python 3.x added a to_bytes() method to the integer
    class. We can't use this just yet, but when we drop python 2.x support we will.
---
 stem/client/datatype.py        | 9 +++++++++
 stem/descriptor/hsv3_crypto.py | 8 +++++---
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/stem/client/datatype.py b/stem/client/datatype.py
index 59a0c167..fa393d30 100644
--- a/stem/client/datatype.py
+++ b/stem/client/datatype.py
@@ -381,6 +381,15 @@ class Size(Field):
       elif content < 0:
         raise ValueError('Packed values must be positive (attempted to pack %i as a %s)' % (content, self.name))
 
+    # TODO: When we drop python 2.x support this can be simplified via
+    # integer's to_bytes() method. For example...
+    #
+    #   struct.pack('>Q', my_number)
+    #
+    # ... is the same as...
+    #
+    #   my_number.to_bytes(8, 'big')
+
     try:
       packed = struct.pack(self.format, content)
     except struct.error:
diff --git a/stem/descriptor/hsv3_crypto.py b/stem/descriptor/hsv3_crypto.py
index 7c641363..1da07b1b 100644
--- a/stem/descriptor/hsv3_crypto.py
+++ b/stem/descriptor/hsv3_crypto.py
@@ -1,6 +1,8 @@
 import base64
 import binascii
 import hashlib
+import struct
+
 import stem.prereq
 
 # SHA3 requires Python 3.6+ *or* the pysha3 module...
@@ -166,8 +168,8 @@ def _ciphertext_mac_is_valid(key, salt, ciphertext, mac):
     raise ImportError(SHA3_ERROR_MSG % 'Hidden service validation')
 
   # Construct our own MAC first
-  key_len = len(key).to_bytes(8, 'big')
-  salt_len = len(salt).to_bytes(8, 'big')
+  key_len = struct.pack('>Q', len(key))
+  salt_len = struct.pack('>Q', len(salt))
 
   my_mac_body = b'%s%s%s%s%s' % (key_len, key, salt_len, salt, ciphertext)
   my_mac = hashlib.sha3_256(my_mac_body).digest()
@@ -204,7 +206,7 @@ def _decrypt_descriptor_layer(ciphertext_blob_b64, revision_counter, public_iden
   print('===')
 
   # INT_8(revision_counter)
-  rev_counter_int_8 = revision_counter.to_bytes(8, 'big')
+  rev_counter_int_8 = struct.pack('>Q', revision_counter)
   secret_input = b'%s%s%s' % (secret_data, subcredential, rev_counter_int_8)
   secret_input = secret_input
 



_______________________________________________
tor-commits mailing list
tor-commits@xxxxxxxxxxxxxxxxxxxx
https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits