【问题标题】:Python - How to Decode a RFC2045 Base64 StringPython - 如何解码 RFC2045 Base64 字符串
【发布时间】:2019-08-15 19:36:56
【问题描述】:

找不到解码 RFC2045 格式 base64 字符串的方法

我正在尝试解码 RFC2045 格式的 base64 字符串 inn Python 3,但找不到与 org.apache.commons.codec.binary.Base64.decodeBase64 相同结果的方法。

这里是Java代码:

import static org.apache.commons.codec.binary.Base64.decodeBase64;

String str1 = "j-FH-F9__CIiwyg0o3A2mKflRBnxZSMwktDJQyvRevc";
byte[] b1 = decodeBase64(str1);
System.out.println(b1.length + " " + b1);

还有 Python 3 代码:

import base64
from email import base64mime

def bytes2list(bdata):
    return [b if b < 128 else b - 256 for b in bdata]

b64str = 'j-FH-F9__CIiwyg0o3A2mKflRBnxZSMwktDJQyvRevc'
b64str += "=" * ((4 - len(b64str) % 4) % 4)
b1 = base64.b64decode(b64str)
b2 = base64mime.decode(b64str)
print(len(b1), bytes2list(b1))
print(len(b2), bytes2list(b2))

Java 程序输出:32 [-113, -31, 71, -8, 95, 127, -4, 34, 34, -61, 40, 52, -93, 112, 54, -104, -89, -27, 68, 25, -15, 101, 35, 48, -110, -48, -55, 67, 43, -47, 122, -9]

Python 输出:29 [-116, 81, -59, -12, 34, 34, -61, 40, 52, -93, 112, 54, -104, -89, -27, 68, 25, -15, 101, 35, 48, -110, -48, -55, 67, 43, -47, 122, -9] 用于 base64.b64decodebase64mime.b64decode

我希望这不是一个非常罕见的情况,但只是找不到正确的方法。有什么提示吗?

【问题讨论】:

  • str1 = 'j-...' 在 Java 中无效 jshell&gt; Base64.getDecoder().decode("j-FH-F9__CIiwyg0o3A2mKflRBnxZSMwktDJQyvRevc") | Exception java.lang.IllegalArgumentException: Illegal base64 character 2d(减号无效 Base64)
  • 比较宽松:jshell&gt; Base64.getMimeDecoder().decode("j-FH-F9__CIiwyg0o3A2mKflRBnxZSMwktDJQyvRevc") ==&gt; byte[29] { -116, 81, -59, -12, 34, 34, -61, 40, 52, -93, 112, 54, -104, -89, -27, 68, 25, -15, 101, 35, 48, -110, -48, -55, 67, 43, -47, 122, -9 } - 考虑使用 Java 自带的解码器...
  • 我使用 Groovy 运行 Java 代码。抱歉错过了单引号和双引号问题
  • 数据是用 RFC 2045 编码的,只有 Apache 通用的才能正确解码。需要用 Python 3 做同样的事情
  • 数据不是根据 RFC 2045 编码的。它是根据 RFC 4648 第 5 节编码的,使用带有“-”和“_”的“URL 和文件名安全字母”代替通常的“+” ' 和 '/' 字符。要在 Python 中解码此数据,请使用 base64 模块的 urlsafe_b64decode 方法。

标签: java python base64 apache-commons


【解决方案1】:

How to decode base64 url in python? 中找到答案。代码应该是:

b1 = base64.urlsafe_b64decode(b64str)

【讨论】:

    猜你喜欢
    • 2011-10-18
    • 2020-12-26
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2011-10-31
    相关资源
    最近更新 更多