Base64 decode gives different results in Java and Ruby

偶尔善良 提交于 2019-12-23 18:42:03

问题


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.


回答1:


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...)




回答2:


Are you trying to print out into Text? that won't work, try using a ByteArray to store the decoded string.

Example:

BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);



回答3:


The decoded string actually starts with 'FLV':

require 'base64'
Base64.decode64('RkxWAQEAAAAJAAAAABIAAK4AAAAAAAAAAgAKb25NZXRhRGF0YQgAAAAHAAV3aWR0aABAdAAAAAAA AAAGaGVpZ2h0AEB0AAAAAAAAAAlmcmFtZXJhdGUAQBAAAAAAAAAADHZpZGVvY29kZWNpZABACAAA AAAAAAAMY2FuU2Vla1RvRW5kAQEAD21ldGFkYXRhY3JlYXRvcgIAKVNpbXBsZUZMVldyaXRlci5h cyB2MC44IHplcm9wb2ludG5pbmUuY29tAAAJ')
=> "FLV\001\001\000\000\000\t\000\000\000\000\022\000\000\256\000\000\000\000\000\000\000\002\000\nonMetaData\b\000\000\000\a\000\005width\000@t\000\000\000\000\000\000\000\006height\000@t\000\000\000\000\000\000\000\tframerate\000@\020\000\000\000\000\000\000\000\fvideocodecid\000@\b\000\000\000\000\000\000\000\fcanSeekToEnd\001\001\000\017metadatacreator\002\000)SimpleFLVWriter.as v0.8 zeropointnine.com\000\000\t"

JRuby 1.6.1



来源:https://stackoverflow.com/questions/6020674/base64-decode-gives-different-results-in-java-and-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!