0

I have encoded a string to integer in the following way in python:

b = bytearray()
b.extend(input_number_or_text.encode('ascii'))
input_number_or_text = int.from_bytes(b,byteorder='big', signed=False)

I am encrypting this integer to get a new value and subsequently decrypting to get back the original integer.

Now how do I get back the string from the integer

I have tried the following method for decryption:

decrypted_data.to_bytes(1,byteorder='big').decode('ascii')

but I get int too big to convert error.

How to fix this problem?

twothreezarsix
  • 375
  • 3
  • 13

2 Answers2

0

The byte representation of an integer is different than a string.

For example - 1 , '1', 1.0 all look different when looking at the byte representation.

From the code you supply - b.extend(input_number_or_text.encode('ascii'))

and int.from_bytes(b,byteorder='big', signed=False)

Seems like your encoding a string of a number, and trying to decode it as a int.

See the next example:

In [3]: b = bytearray()
In [4]: a = '1'
In [5]: b.extend(a.encode('ascii'))
In [6]: int.from_bytes(b,byteorder='big',signed=False)
Out[6]: 49

If you are encoding a string, you should first decode a string, and then convert to int.

In [1]: b = bytearray()
In [2]: a = '123'
In [3]: b.extend(a.encode('ascii'))
In [4]: decoded = int(b.decode('ascii'))
In [5]: decoded
Out[5]: 123
Dinari
  • 2,487
  • 13
  • 28
0

You told it the int should be convertable to a length 1 byte string. If it's longer, that won't work. You can remember the length, or you can guess at it:

num_bytes = (decrypted_data.bit_length() + 7) // 8
decrypted_data.to_bytes(num_bytes, byteorder='big').decode('ascii')

Adding 7 and floor-dividing by 8 ensures enough bytes for the data. -(-decrypted_data.bit_length() // 8) also works (and is trivially faster on Python), but is a bit more magical looking.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271