Преобразование гекса в целое число в Python - эквивалент для ToInt64 в C# - PullRequest
0 голосов
/ 31 января 2020

Я пытаюсь преобразовать sha256 га sh в целое число. Это работает в C#, но я не могу заставить его работать в Python.

C# Version :
string inputString = "TestString";
            SHA256 sha256Hash = SHA256.Create();
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(inputString));
            //Read the Bytes and print
            var sb = new StringBuilder(bytes.Length * 2);
            sb = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
            {
                sb.Append(b.ToString("x2"));
            }
            Console.WriteLine("Bytes: " + sb);            
            Console.WriteLine("ConvertedInt: " + BitConverter.ToInt64(bytes));
Output :
Bytes: 6dd79f2770a0bb38073b814a5ff000647b37be5abbde71ec9176c6ce0cb32a27
ConvertedInt: 4088037490330425197

Вышеуказанные байты и целочисленные значения печатаются, как и ожидалось. Попытка сделать то же самое в Python, но не удалось преобразовать в одно целое число.

import hashlib
hashobj = hashlib.sha256("TestString".encode('utf-8')).hexdigest()
print(hashobj)

#Tried Option 1:
print(f"Option 1 prints:\r")
print(int(hashobj,32))

#Tried Option 2:
print(f"Option 1 prints:\r")
print(int(hashobj,16))

Output:
6dd79f2770a0bb38073b814a5ff000647b37be5abbde71ec9176c6ce0cb32a27
Option 1 prints:
428476861264242379186014021585258195649378281633207959348811042267114033125399631735390859241543
Option 1 prints:
49683071055471546380350462257487304408748464885741562355821390565893091830311

Как я могу преобразовать hashobj в 64-битное целое число в python? Просто пытаюсь получить одно и то же целочисленное значение в python, спасибо за любую помощь.

Редактировать 1:

После ответа от @Sweeper и @Recursing смог продолжить, но проблема, когда полученное целое число подписано.
Случай 1: Hex для Integer равен + ve, когда я пытаюсь по модулю int (8 байтов) с числом, скажем 300, дать ожидаемый результат 108.
Случай 2 & Случай 3: Hex для Integer - -ve, тогда я должен прочитать переменное число байтов, 7 байтов для случая 2 и 9 байтов для случая 3, а затем по модулю 300 дать ожидаемый результат 108.

Вопрос: Как определить количество байтов для чтения, когда целое число равно -ve, чтобы получить тот же результат? Спасибо.

#Case 1
hash_bytes = hashlib.sha256("098C10227K3R".encode('utf-8')).digest()
print("Case 1 : Is Positive : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) > 0))
print("Case 1 : IntegerValue : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True)))
print("Case 1 : 8 Bytes:")
print(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) % 300)

#Case 2
hash_bytes = hashlib.sha256("159YK282MS3T".encode('utf-8')).digest()
print("Case 2 : Is Positive : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) > 0))
print("Case 2 : IntegerValue : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True)))
print("Case 2 : 8 Bytes:")
print(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) % 300)
print("Case 2 : 7 Bytes:")
print(int.from_bytes(hash_bytes[:7], byteorder="little", signed=True) % 300)

#Case 3
print("Case 3:")
hash_bytes = hashlib.sha256("17FK427W501L".encode('utf-8')).digest()
print("Case 3 : Is Positive : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) > 0))
print("Case 3 : IntegerValue : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True)))
print("Case 3 - 8 Bytes:")
print(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) % 300)
print("Case 3 - 9 Bytes:")
print(int.from_bytes(hash_bytes[:9], byteorder="little", signed=True) % 300)

Output:
Case 1 : Is Positive : True
Case 1 : IntegerValue : 9212408962392255108
Case 1 : 8 Bytes:
108
Case 2 : Is Positive : False
Case 2 : IntegerValue : -5822649536180381508
Case 2 : 8 Bytes:
192
Case 2 : 7 Bytes:
Case 3 : IntegerValue 7 bytes: 14015580891781308
108
Case 3:
Case 3 : Is Positive : False
Case 3 : IntegerValue : -2669588811718081008
Case 3 - 8 Bytes:
192
Case 3 - 9 Bytes:
Case 3 : IntegerValue 9 bytes: -445391446580747319792
108

1 Ответ

0 голосов
/ 31 января 2020

Как сказал @Sweeper, код C# хранит только первые 8 байтов га sh и преобразует его в целое число

В python вы можете сделать:

import hashlib
hash_bytes = hashlib.sha256("TestString".encode('utf-8')).digest()
first_bytes = hash_bytes[:8]
print(int.from_bytes(first_bytes, byteorder="little", signed=True))

В качестве альтернативы можно использовать модуль struct в стандартной библиотеке: https://docs.python.org/3/library/struct.html

print(struct.unpack("q", first_bytes))
...