简体   繁体   English

Java Base64编码提供与C base64编码不同的结果

[英]Java Base64 encode gives different results than C base64 encode

I try to encode this byte array: 我尝试编码这个字节数组:

[237, 217, 204, 218, 109, 227, 157, 145, 35, 152, 85, 142, 182, 180, 120, 8]

Using Java library org.apache.commons.codec.binary.Base64.encodeBase64 and org.bouncycastle.util.encoders.Base64.encode this is the results: 使用Java库org.apache.commons.codec.binary.Base64.encodeBase64org.bouncycastle.util.encoders.Base64.encode这是结果:

[55, 100, 110, 77, 50, 109, 51, 106, 110, 90, 69, 106, 109, 70, 87, 79, 116, 114, 82, 52, 67, 65, 61, 61]

(note the double '=' padding character at the end) (注意末尾的双'='填充字符)

Using base64.c Copyright (c) 1995-2001 Kungliga Tekniska Högskolan (Royal Institute of Technology, Stockholm, Sweden) this is the output: 使用base64.c Copyright (c) 1995-2001 Kungliga Tekniska Högskolan (Royal Institute of Technology, Stockholm, Sweden)这是输出:

[55, 100, 110, 77, 50, 109, 51, 106, 110, 90, 69, 106, 109, 70, 87, 79, 116, 114, 82, 52, 67, 66, 72, 114]

Can anyone explain why? 有谁能解释为什么? How can I make the Java/C library works the same way? 如何使Java / C库以相同的方式工作?

Every Base64 ASCII character holds 6 bits information (2 6 = 64), so 4 Base64 characters hold 3 bytes information. 每个Base64 ASCII字符保存6位信息(2 6 = 64),因此4个Base64字符包含3个字节信息。 You have 16 bytes, so one byte remains at the end, needing 2 Base64 characters, and to make the group up to 4 chars, two padding = s are added. 你有16个字节,所以一个字节保留在最后,需要2个Base64字符,并且要使组最多4个字符,添加两个padding = s。

Mind: with JavaSE 8 came a class Base64 to replace several older class around. 介意:用JavaSE 8来了一个类Base64来替换几个老类。

Base64 has several fields of application, with various little changes: padding can be left out, line breaks added to limit line length, and so on. Base64有几个应用领域,各种变化很小:可以省略填充,添加换行符以限制行长度,等等。 Java 8's Base64 even has an option for a non-compatible URL and file name safeversion, where + and / are replaced. Java 8的Base64甚至可以选择不兼容的URL和文件名safeversion,其中+/被替换。

Base64适用于3个字节的块, = padding可以使输出大小达到3的倍数。这个填充是可选的,如果不存在那么你可以通过在尝试之前检查数组长度来手动添加它使用Java代码进行解码。

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

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