Decoding Error: Int too big to convert while decrypting

Decoding Error: Int too big to convert while decrypting

我在 python 中按以下方式将字符串编码为整数:

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

我正在加密这个整数以获得一个新值,然后解密以取回原始整数。

现在如何从整数中取回字符串

我试过以下解密方法:

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

但我收到 int too big to convert 错误。

如何解决这个问题?

整数的字节表示与字符串不同。

例如 - 1'1'1.0 在查看字节表示时看起来都不一样。

根据您提供的代码 - b.extend(input_number_or_text.encode('ascii'))

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

好像你编码了一个数字字符串,并试图将它解码为一个整数。

看下一个例子:

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

如果您正在编码一个字符串,您应该先解码一个字符串,然后再转换为 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

你告诉它 int 应该可以转换为长度为 1 字节的字符串。如果它更长,那将不起作用。你可以记住长度,也可以猜一下:

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

加7再除以8保证数据有足够的字节。 -(-decrypted_data.bit_length() // 8) also works(在 Python 上速度更快),但看起来更神奇。