users@jersey.java.net

Re: [Jersey] Re: Base64.encode() ok to use?

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Thu, 10 Jun 2010 15:33:19 -0700

On Thu, Jun 10, 2010 at 2:22 PM, Christopher Piggott <cpiggott_at_gmail.com> wrote:
> Crud, you know what the problem is?  Bytes in java are signed, so if
> the SHA1 MessageDigest gives a character from 0x80 to 0xFF, then java
> will pass that along OK but here:
>
>            encodedData[encodedIndex] = lookUpBase64Alphabet[b1 >> 2];
>
> and all similar places it will be treated as a negative number, i.e. a
> negative index into the array, and it will blow up.
>
> I think these things need to be cast to integers to work correctly ...

Cast won't work (in fact, implicit cast with sign extension is what
causes the problem), but idiom to use is 'b1 & 0xFF' (which is ugly
but necessary).
Another minor flaw in code is to rely on default platform encoding
when constructing String, but it shouldn't have much impact since
base64 uses ascii (unless one uses non-ascii-compatible encoding as
platform default -- better not run it on a mainframe :-) )

-+ Tatu +-