Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 decode gives different results in Java and Ruby

Tags:

java

ruby

base64

I am decoding some text using Base64. I have tried three different libraries (commons Base64, Java.misc., and also java.mail) in Java and all of them produce same result for the following text, which is not right.

However when I use Ruby to decode the below string I get different output. I get the right result using Ruby. The Ruby code is print Base64.decode64('<Below String>'), the string is

RkxWAQEAAAAJAAAAABIAAK4AAAAAAAAAAgAKb25NZXRhRGF0YQgAAAAHAAV3aWR0aABAdAAAAAAA
AAAGaGVpZ2h0AEB0AAAAAAAAAAlmcmFtZXJhdGUAQBAAAAAAAAAADHZpZGVvY29kZWNpZABACAAA
AAAAAAAMY2FuU2Vla1RvRW5kAQEAD21ldGFkYXRhY3JlYXRvcgIAKVNpbXBsZUZMVldyaXRlci5h
cyB2MC44IHplcm9wb2ludG5pbmUuY29tAAAJ

The output should start with FLV. I am not sure what I am missing and why the output is different using Java.

like image 342
firemonkey Avatar asked Sep 06 '26 11:09

firemonkey


1 Answers

The result of decoding base64 is binary data. You shouldn't really try to print it as if it were text.

Without knowing Ruby, I'd expect the result of calling Base64.decode64 to be some sort of byte array... and that could be converted into text in any number of ways.

Look at the bytes of what's returned to find out whether or not it's correct.

(It's unfortunate that as far as I can see, the documentation for Base64.decode64 gives examples of exactly the kind of thing you're doing - treating the result of a base64 decode operation as text. It's not clear what type of data is actually returned. This sort of thing is why I still like statically typed languages...)

like image 97
Jon Skeet Avatar answered Sep 07 '26 23:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!