Theo Jouret
Theo Jouret

Reputation: 113

Base 64 decoding byte[] casted into a string

I got some encoded log information, casted into a string for transmitting purpose (the cast might be ugly but it works).

I'm trying to cast it back to a byte[] in order to decode it but it's not working:

byte[] encodedBytes = android.util.Base64.encode((login + ":" + password).getBytes(), NO_WRAP);
String encoded = "Authentification " + encodedBytes;

String to_decode = encoded.substring(17);
byte[] cast1 = to_decode;            // error
byte[] cast2 = (byte[]) to_decode;   // error
byte[] cast3 = to_decode.getBytes();
// no error, but i get something totally different from encodedBytes (the array is even half the size of encodedBytes)
// and when i decode it i got an IllegalArgumentException

these 3 casts are not working, any idea?

Upvotes: 0

Views: 150

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499780

There are multiple problems here.

In general, you need to use Base64.decode in order to reverse the result of Base64.encode:

byte[] data = android.util.Base64.decode(to_decode, DEFAULT);

In general, you should always ask yourself "How did I perform the conversion from type X to type Y?" when working out how to get back from type Y to type X.

Note that you've got a typo in your code too - "Authentification" should be "Authentication".

However, you've also got a problem with your encoding - you're creating a byte[], and using string concatenation with that will call toString() on the byte array, which is not what you want. You should call encodeToString instead. Here's a complete example:

String prefix = "Authentication "; // Note fix here...
// TODO: Don't use basic authentication; it's horribly insecure.
// Note the explicit use of ASCII here and later, to avoid any ambiguity.
byte[] rawData = (login + ":" + password).getBytes(StandardCharsets.US_ASCII);
String header = prefix + Base64.encodeToString(rawData, NO_WRAP);

// Now to validate...
String toDecode = header.substring(prefix.length());
byte[] decodedData = Base64.decode(toDecode, DEFAULT);
System.out.println(new String(decodedData, StandardCharsets.US_ASCII));

Upvotes: 4

Related Questions