sdfjl
sdfjl

Reputation: 23

java base64.deocde to python3

I have a piece of java code

    enter code here
    byte[] random1 = Base64.getDecoder().decode(arr.getString(2));
    byte[] test1 = "/bCN99cbY13kwEf+wnRErg".getBytes(StandardCharsets.ISO_8859_1);
    System.out.println(test1.length);    // #22
    System.out.println(Base64.getDecoder().decode(test1).length);    // #16

I am trying to use python3 and I get an error.

    text = bytes("/bCN99cbY13kwEf+wnRErg", encoding='iso-8859-1')
    print(len(base64.b64decode(text)))

    # Traceback (most recent call last):

    # File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\base64.py", line                 
    # 546, in decodebytes
    #    return binascii.a2b_base64(s)
    # binascii.Error: Incorrect padding

How can I use python3 to implement the functions on the java code to achieve decode length=16

Upvotes: 2

Views: 102

Answers (1)

JANO
JANO

Reputation: 3076

The problem is that your Base64 encoded array is missing the padding, which is not always required.

It is no problem in Java as the Decoder does not require it:

The Base64 padding character '=' is accepted and interpreted as the end of the encoded byte data, but is not required.

In contrast, the Python b64decode(s) method requires the padding and throws an error if it is missing.

A binascii.Error exception is raised if s is incorrectly padded.

I found a simple solution in this answer: Always adding the maximum padding at the end of the byte array (two equal signs ==). The b64decode(s) method simply ignores the padding if it is too long and so it always works.

You only have to change your code slightly for it to work:

text = bytes("/bCN99cbY13kwEf+wnRErg", encoding='iso-8859-1')
padded_text = text + b'=='
result = base64.b64decode(padded_text)

print(len(result))

The output is 16 identical to the Java output.

Upvotes: 1

Related Questions