Python-如何解码RFC2045 Base64字符串

时间:2019-03-25 14:17:12

标签: java python base64 apache-commons

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

我正在尝试在Python 3中解码RFC2045格式的base64字符串,但找不到与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.b64decode的{​​{1}}

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

1 个答案:

答案 0 :(得分:0)

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

b1 = base64.urlsafe_b64decode(b64str)