0

I am trying to implement a protocol described in the paper Private Data Aggregation with Groups for Smart Grids in a Dynamic Setting using CRT in python.

In order to do this, I need to calculate the following value:

enter image description here

I know that since python 3.6, you can calculate a SHA3 value as follows:

import hashlib
hash_object = hashlib.sha3_512(b'value_to_encode')
hash_value = hash_object.hexdigest()

I was wondering you should solve this, since, as far as I know, a SHA-3 function returns a string and therefore cannot be calculated in a function with to the power of n.

What am I overlooking?

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
hY8vVpf3tyR57Xib
  • 3,574
  • 8
  • 41
  • 86
  • 1
    When you pass a string data type to python's internal hash functions I would use the method: a_string_data_type.encode('utf-8'). You can have silent failure without the encoding step with some versions of python. – Q-Club Jun 16 '17 at 22:40
  • @back_seat_driver: `b'value_to_encode'` is not a string type, it's a bytes object. – President James K. Polk Nov 06 '17 at 15:12

1 Answers1

1

If we define a hash function $H: \{0, 1\}^* \rightarrow \{0, 1\}^n$, that is one that produces an $n$ bit output, we can always interpret the binary data $h$ that it outputs as an integer. The integer value of this digest is $\sum_{i=0}^n h_i 2^i$, in other words the digest is a base 2 representation of the integer.

In your case, since python has a notion of types, we need to take the binary string and convert it to an integer type. The builtin int function can do this for us:

int(x=0) -> integer

int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.

>>> int('0b100', base=0)

4

The hexdigest call will return a hex string which is base 16, so you would want to do something like int_value = int(hash_value, 16).

puzzlepalace
  • 660
  • 5
  • 13
  • The `.digest()` method will output a bytes object, so constructing the int using [`int.from_bytes(...)`](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types) is another option that is probably a bit faster. Of course string conversion to/from hex is much faster than to/from decimal, so the difference should be minimal. – President James K. Polk Nov 06 '17 at 15:17