Furkan Halil Er
Furkan Halil Er

Reputation: 1

sun.misc.BASE64Encoder to java.util.Base64 migration problem

There is an old project at work that was written in a version prior to Java 8.

We are migrating this project to Java 11. In the old project, there is a method that takes a password variable and decodes it from Base64:

String password = "123456";
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(password);
// do something with bytes

Since I was asked to copy this code exactly as it is, I am transferring it to the Java 11 project without any refactoring, using the java.util.Base64 classes, as follows:

String password = "123456";
byte[] bytes = Base64.getDecoder().decode(password);
// do something with bytes

The problem here is this:

In the old project, the byte array generated by the decoder.decodeBuffer(password); operation is as follows: [-41, 109, -8, -25, -83, -8].

However, in the new project, the byte array generated by Base64.getDecoder().decode(password); operation is as follows: [-41, 109, -8, -25].

So, as you can see, while the old library creates a 6-digit array, the new library creates a 4-digit array. However, these four digits are the same as the other, 2 bytes are missing. This causes subsequent code to behave differently.

How can I solve this? How can I ensure that the decode operation of the new Base64 class gives the same result as the operation in the old class?

I tried all methods of the new Base64 class and expected the byte arrays to be same, but cannot succeed.

Upvotes: -1

Views: 81

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198371

Fundamentally, it seems that your issue is that you are decoding passwords as if they were valid Base64 strings.

123456 isn't a valid Base64 string. It is not the result of encoding any real sequence of bytes.

So what you are seeing is two different strategies for trying to cope with invalid Base64. java.util.Base64 simply gives up after the input stops making sense as Base64. sun.misc appears to be giving you nonsensical bytes that don't actually encode back into the same input.

I wouldn't expect java.util.Base64 to actually have a reasonable way of getting the old, even more nonsensical behavior.

(That said, extremely strange things seem likely to happen if your password uses other characters not valid in Base64, such as every symbol except +, /, and =...)

I suppose what I'm really telling you is that this password system is extremely broken and absolutely needs to be fully replaced, but that may already be clear.

Upvotes: 4

Related Questions