Last week I was trying to encode some encrypted data as a cookie. After encrypting the data, I was left with a byte[] array. So all that was left was to create a string, and then fix all the strange characters... preferably by base64 encoding it, for example.
That worked fine, until I wanted to decode the string. All of a sudden the byte[] array was no longer the same... well, sometimes, it wasn't.
What was actually necessary was encoding those bytes to a string... say a base64 string! Most base64 libraries support encoding bytes to a base64 byte[] array, and the apache commons codec also allows encoding to a string.
Better yet, they allow encoding to an url safe string, which does not contain +,= or /. And it has a proper decoding of such a string too. Presto!
That worked fine, until I wanted to decode the string. All of a sudden the byte[] array was no longer the same... well, sometimes, it wasn't.
byte[] data = new byte[20]; new Random().nextBytes[data]; // fill with some random data. String myString = new String(data); byte[] fromString = myString.getBytes(); for(int i = 0; i < data.length; i++) assert(data[i] == fromString[i])The code above will fail... from time to time. This is rather strange, and not directly obvious from the javadoc. First I considered if it was an encoding problem. This only compounded the issue, as
new String(data, "UTF-16" ).getBytes().lengthis twice the size of the original data. That was leading nowhere. After looking and testing I finally figured it out: Java String constructor with bytes assumed those bytes are from a string! If they are not, then the (logical) idempotence of new String().getBytes() does not hold!
What was actually necessary was encoding those bytes to a string... say a base64 string! Most base64 libraries support encoding bytes to a base64 byte[] array, and the apache commons codec also allows encoding to a string.
Better yet, they allow encoding to an url safe string, which does not contain +,= or /. And it has a proper decoding of such a string too. Presto!
Reacties
Een reactie posten