将Integer值转换为base64,然后对其进行解码以获取纯文本

时间:2019-03-26 09:56:22

标签: python base64

我给了这个数字427021005928,我应该将其更改为base64编码的字符串,然后对base64字符串进行解码以获取纯文本。

当转换为二进制时,此十进制值427021005928给出110001101101100011011111110111010001101000,它对应于'Y2xvdGg =',这就是我想要的。从(https://cryptii.com/pipes/binary-to-base64)获得转换

然后最后我解码'Y2xvdGg ='以获取文本布料。

我的问题是我不知道如何使用Python从十进制或二进制值中获取'Y2xvdGg ='

我们将不胜感激!

注意:开始时我只有这个值427021005928。我需要得到base64和纯文本答案。

5 个答案:

答案 0 :(得分:3)

尝试

number = 427021005928

encode = base64.b64encode(bytes(number))

decode = base64.b64decode(encodeNumber)

答案 1 :(得分:2)

一种优雅的方法是使用[Python 3]: struct - Interpret bytes as packed binary data,但是鉴于 Python 的数字大小不是固定的,因此需要进行一些额外的计算(例如,数字为 5 个字节)。

显然,在线转换器将 base64 编码应用于数字的内存表示形式,该编码可以通过[Python 3]: int.to_bytes(length, byteorder, *, signed=False)获得( endianness 很重要,在这种情况下,它是 big ):

对于向后过程,需要相反的步骤。有2种选择:

  • 手动完成的操作(这也可以应用于“转发”过程)
  • 使用int.from_bytes
>>> import base64
>>>
>>> number = 427021005928
>>>
>>> number_bytes = number.to_bytes((number.bit_length() + 7) // 8, byteorder="big")  # Here's where the magic happens
>>> number_bytes, number_bytes.decode()
(b'cloth', 'cloth')
>>>
>>> encoded = base64.b64encode(number_bytes)
>>> encoded, encoded.decode()  # Don't let yourself tricked by the variable and method names resemblance
(b'Y2xvdGg=', 'Y2xvdGg=')
>>>
>>> # Now, getting the number back
...
>>> decoded = base64.b64decode(encoded)
>>> decoded
b'cloth'
>>>
>>> final_number0 = sum((item * 256 ** idx for idx, item in enumerate(reversed(decoded))))
>>> final_number0
427021005928
>>> number == final_number0
True
>>>
>>> # OR using from_bytes
...
>>> final_number1 = int.from_bytes(decoded, byteorder="big")
>>> final_number1
427021005928
>>> final_number1 == number
True

有关按位运算的更多详细信息,请检查[SO]: Output of crc32b in PHP is not equal to Python (@CristiFati's answer)

答案 2 :(得分:1)

尝试一下(https://docs.python.org/3/library/stdtypes.html#int.to_bytes

>>> import base64
>>> x=427021005928
>>> y=x.to_bytes(5,byteorder='big').decode('utf-8')
>>> base64.b64encode(y.encode()).decode()
'Y2xvdGg='
>>> y
'cloth'

答案 3 :(得分:0)

您可以使用python进行以下转换

首先使用以下语法导入base64

>>> import base64

要将文本转换为base64 ,请执行以下操作

编码

>>> base64.b64encode("cloth".encode()).decode()
    'Y2xvdGg='

解码

>>> base64.b64decode("Y2xvdGg=".encode()).decode()
    'cloth'

答案 4 :(得分:0)

下面的函数将一个无符号的 64 位整数转换为 base64 表示,然后再返回。这对于编码数据库密钥特别有用。

我们首先使用小端将整数编码为字节数组,并自动删除任何额外的前导零。然后转换为 base64,删除不必要的 = 符号。请注意标志 url_safe,它使解决方案不符合 base64,但对 URL 更有效。

def int_to_chars(number, url_safe = True):
    '''
    Convert an integer to base64. Used to turn IDs into short URL slugs.
    :param number:
    :param url_safe: base64 may contain "/" and "+", which do not play well
                     with URLS. Set to True to convert "/" to "-" and "+" to
                     "_". This no longer conforms to base64, but looks better
                     in URLS.
    :return:
    '''
    if number < 0:
        raise Exception("Cannot convert negative IDs.")
    # Encode the long, long as little endian.
    packed = struct.pack("<Q", number)
    # Remove leading zeros
    while len(packed) > 1 and packed[-1] == b'\x00':
        packed = packed[:-1]
    encoded = base64.b64encode(packed).split(b"=")[0]
    if url_safe:
        encoded = encoded.replace(b"/", b"-").replace(b"+", b".")
    return encoded

def chars_to_int(chars):
    '''Reverse of the above function. Will work regardless of whether
    url_safe was set to True or False.'''
    # Make sure the data is in binary type.
    if isinstance(chars, six.string_types):
        chars = chars.encode('utf8')
    # Do the reverse of the url_safe conversion above.
    chars = chars.replace(b"-", b"/").replace(b".", b"+")
    # First decode the base64, adding the required "=" padding.
    b64_pad_len = 4 - len(chars) % 4
    decoded = base64.b64decode(chars + b"="*b64_pad_len)
    # Now decode little endian with "0" padding, which are leading zeros.
    int64_pad_len = 8 - len(decoded)
    return struct.unpack("<Q", decoded + b'\x00' * int64_pad_len)[0]