python - Python 中 base64 编码/解码的额外新行?

标签 python python-3.x base64 decode encode

我写了这些实用函数:

import base64

def der2str(der):
    return bin2str( base64.encodebytes(der) )

def str2der(str_):
    return base64.b64decode( str2bin(str_) )

def bin2str(binary):
    return binary.decode('utf8')

def str2bin(str_):
    return str_.encode('utf8')

我运行的:

if __name__ == '__main__':
    test = 'MIIEowIBAAKCAQEA6cVU+6GZyr1jaxvJcLEdRb9cicL/4Soe/HqN+gE/UdM5C71aG6HhNSplj1qi\nX8Abffen'
    print(test)
    print(der2str(str2der(test)))

但是输出是:

MIIEowIBAAKCAQEA6cVU+6GZyr1jaxvJcLEdRb9cicL/4Soe/HqN+gE/UdM5C71aG6HhNSplj1qi
X8Abffen
MIIEowIBAAKCAQEA6cVU+6GZyr1jaxvJcLEdRb9cicL/4Soe/HqN+gE/UdM5C71aG6HhNSplj1qi
X8Abffen


为什么我在第二次打印时多了这两条新行?

[编辑]
根据标记的答案,使用 return bin2str( base64.b64encode(der) ),只要输入字符串 test 不包含任何 '\n '.

如果有人需要换行符,则字符串必须以 '\n' 结尾,断言 assert(test == der2str(str2der(test))) 才能通过.

最佳答案

base64.encodebytes(s) 的文档声明它插入换行符

Encode the bytes-like object s, which can contain arbitrary binary data, and return bytes containing the base64-encoded data, with newlines (b'\n') inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME).

您可能想使用 base64.b64encode相反。

关于python - Python 中 base64 编码/解码的额外新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61026486/

相关文章:

python - 导入错误: DLL load failed: %1 is not a valid Win32 application while importing win32com

XSLT:将 base64 数据转换为图像文件

javascript - 本地存储中出现损坏的 PDF 文件错误

Python-将数据框除以数字列表,包括零

python - 在 while 循环中输出 re.search 和 re.match 时遇到问题

python - 如何在 Windows 中设置 PYTHONPATH?

python-3.x - 在 python 中使用 lstm 预测值时,“numpy.ndarray”对象没有属性 'iterrows'

python - 一旦所有页面都循环并将值附加到我的列表中,如何将抓取的值存储到数据框中?

javascript - 将 Base64 block 写入 writestream

python - 是否可以使用discord.py 查找流式YouTube 音频(从视频中给定的时间戳开始播放)?