2

I am trying to decode a Base64 string from my authentication headers in Java. I am certain that the request being sent has a valid Base64 encoded string in the authentication header. Here is my decoding code:

HttpServletRequest request = (HttpServletRequest) req;
byte[] test = new Base64().decode(request.getHeader("Authorization"));

Before I decode the request it looks like this Basic dXNlcjpmZGdmcw==

After I try to decode it it looks like this: «"qÕÍ•È陑™Ì

I am not sure what I am doing wrong, and no matter what decode utility I use it always ends up looking like gibberish. Thanks for reading.

ikottman
  • 1,996
  • 3
  • 21
  • 23
  • 4
    Make sure the string you pass to decode() starts with dXNl..., not Basic. FYI, the string in your question says: "user:fdgfs". – Olaf Jun 16 '11 at 16:16
  • 1
    http://base64decode.org/ decodes it as user:fdgfs so it's possibly the byte array to string conversion that's screwing up. – Nick Jun 16 '11 at 16:16

2 Answers2

1

Thats because you are trying to decode whole String "Basic dXNlcjpmZGdmcw==" instead of "dXNlcjpmZGdmcw==".

danipenaperez
  • 583
  • 5
  • 12
1
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
System.out.println(new String(decoder.decodeBuffer("dXNlcjpmZGdmcw==")));

Prints user:fdgfs. Note: Decode Base64 data in Java for better solutions. Have you checked what is returned by:

request.getHeader("Authorization")

?

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • I was an idiot and didn't remove the Basic from my string before decoding it, so it was attempting to decode "Basic dXNlcjpmZGdmcw==" instead of "dXNlcjpmZGdmcw==" – ikottman Jun 16 '11 at 16:25
  • Do not use undocumented sun.* libraries in your code. It may not be there next version or a different JVM implementation, and it may change it interface or specification without notice. Remember, if it's a private library I can refactor it to my hearts content as long as I change my ***private*** dependencies on it. – Lawrence Dol Jun 16 '11 at 17:47
  • @Software Monkey: you are absolutely right, that's why I pointed out link to [this](http://stackoverflow.com/questions/469695/decode-base64-data-in-java) question *"for better solutions"*. I actually copied the first answer just to check the supplied Base64. – Tomasz Nurkiewicz Jun 16 '11 at 18:21