【问题标题】:Converting an Integer value to base64, and then decoding it to get a plaintext将Integer值转换为base64,然后解码得到明文
【发布时间】:2019-03-26 09:56:21
【问题描述】:

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

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

最后我解码 'Y2xvdGg=' 得到文字布。

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

我们将不胜感激!

注意:我一开始只有这个值 427021005928。我需要得到 base64 和明文的答案。

【问题讨论】:

  • 我没有得到相同的 base64 字符串。试试import base64; import struct; v=struct.pack('L', v); base64.b64encode(struct.pack('L', v))

标签: python base64


【解决方案1】:

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

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

对于反向过程,需要反向步骤。有两种选择:

  • 手动完成的事情(这也可以应用于“转发”过程)
  • 使用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】:

试试这个 (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'

【讨论】:

  • 更新了答案@martineau
  • 感谢您的回答!
  • 没问题。如果对你有帮助,请点赞/采纳
  • 嗨@Moud :) 如果对您有帮助,请考虑接受答案,也请查看stackoverflow.com/help/someone-answers
【解决方案3】:

试试

number = 427021005928

encode = base64.b64encode(bytes(number))

decode = base64.b64decode(encodeNumber)

【讨论】:

  • encode 和 decode 的值没有打印出来
  • Python 3 中不起作用,而且 不匹配 问题第 2 段! -1.
【解决方案4】:

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

我们首先使用 little endian 将整数编码为字节数组,然后自动删除任何多余的前导零。然后转换为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]

【讨论】:

    【解决方案5】:

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

    首先使用以下语法导入base64

    >>> import base64
    

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

    编码

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

    解码

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

    【讨论】:

    • 这不能回答我的问题!我需要将 427021005928 更改为 'Y2xvdGg='。我在开始时没有值“Y2xvdGg=”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多