简体   繁体   English

Apache通用base64解码和Sun base64解码

[英]Apache commons base64 decode and Sun base64 decode

byte[] commonsDecode = Base64.decodeBase64(data);
debug("The data is " + commonsDecode.length + " bytes long for the apache commons base64 decoder.");
BASE64Decoder decoder = new BASE64Decoder();
byte[] sunDecode = decoder.decodeBuffer(data);
Log.debug("The data is " + sunDecode.length + " bytes long for the SUN base64 decoder.");

Please explain to me why these two method calls would produce different length for the resulting byte arrays. 请解释为什么这两个方法调用会为生成的字节数组生成不同的长度。 I initially thought it might have to do with character encodings but if so I don't understand all of the issues properly. 我最初认为它可能与字符编码有关,但如果是这样,我不能正确理解所有问题。 The above code was executed on the same system and in the same application, in the order shown above. 上述代码按照上面显示的顺序在同一系统和同一应用程序中执行。 So the default character encoding on that system would be the same. 因此该系统上的默认字符编码将是相同的。

The input (test) data: The below is a System.out.println of the Java String. 输入(测试)数据:下面是Java String的System.out.println。

qFkIQgDq jk3ScHpqx8BPVS97YE4pP/nBl5Qw7mBnpSGqNqSdGIkLPVod0pBl Uz7NgpizHDicGzNCaauefAdwGklpPr0YdwCu4wRkwyAuvtDmL0BYASOn2tDw72LMz5FChtSa0CoCBQ2ARsFG2GdflnIWsUuBQapX73ZBMiqqm  ZCOnMRv9Ol8zT1TECddlKZMYAvmjANgq0sBPyUMF7co XY9BYAjV3L/cA8CGQpXGdrsAgjPKMhzk4hh1GAoQ1soX2Dva8p3erPJ4sy2Vcb6lS1Hap9FR0AZFawbJ10FFSTg10wxc24539kYA6xxq/TFqkhaEoSyTqjXjvo1SA==

Apache commons decoder says it's 252 length byte array. Apache commons解码器说它是252个长度的字节数组。 Java Sun decoder says 256. Java Sun解码器说256。

The decoded data is not valid Base64 data. 解码数据无效Base64数据。

Valid Base64 data can contain whitespace. 有效的Base64数据可以包含空格。 Usually, it has a newline every 72 characters. 通常,它每72个字符有一个换行符。 However, your data contains spaces in random places. 但是,您的数据包含随机位置的空格。 If they are removed (as every Base64 decoder is supposed to do), 339 characters remain. 如果它们被删除(因为每个Base64解码器应该这样做),仍然有339个字符。 Yet, valid Base64 data has to be a multiple of 4 characters. 但是,有效的Base64数据必须是4个字符的倍数。

Interestingly, your data contains no plus signs. 有趣的是,您的数据不包含加号。 I suspect it once contained them but they have probably been replaced with spaces somewhere in transmission. 我怀疑它曾经包含它们但它们可能已经被传输中的某个空间所取代。 If you replace all spaces with plus signs, the Base64 data is valid and the decoded data will have a length of 256 bytes: 344 characters / 4 * 3 - 2 padding characters. 如果用加号替换所有空格,则Base64数据有效,解码数据的长度为256字节:344个字符/ 4 * 3 - 2个填充字符。

I further suspect that the Base64 data was used in a URL without proper URL encoding. 我进一步怀疑Base64数据是在没有正确URL编码的URL中使用的。 That's a probable cause for the missing plus signs. 这是失踪加号的可能原因。 Note that Base64 encoded data is not URL safe. 请注意,Base64编码数据不是URL安全的。 Both the plus and the equal signs need to be escaped. 加号和等号都需要转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM