我创建了一些应该可以工作的代码:
String input = "PONT4uYmTYwiP0omcAxZG8a3vKI=";
String expectedOut = "3ce353e2e6264d8c223f4a26700c591bc6b7bca2";
Base64.Decoder decoder = Base64.getDecoder();
byte[] outAsByte = decoder.decode(input);
String output = new String(outAsByte, StandardCharsets.UTF_8);
System.out.println(input);
System.out.println(output);
(基于 How do I decode a base64 encoded string? - 我知道它是用 C# 编写的)
令人惊讶的是,这会输出以下内容:
PONT4uYmTYwiP0omcAxZG8a3vKI=
<?S??&M?"?J&pY???
为什么这会打印一堆乱码而不是预期的输出?
编辑:我使用此 bash 命令得到了预期的输出:
echo -n PONT4uYmTYwiP0omcAxZG8a3vKI= | base64 -d | xxd -p
最佳答案
来自xxd
的手册页
xxd creates a hex dump of a given file or standard input.
您正在对解码值进行十六进制转储。
您可以使用提供的实用程序重现它 here
System.out.println(Hex.encodeHexString(outAsByte));
生成
3ce353e2e6264d8c223f4a26700c591bc6b7bca2
与您的匹配
// 3ce353e2e6264d8c223f4a26700c591bc6b7bca2
String expectedOut = "3ce353e2e6264d8c223f4a26700c591bc6b7bca2";
关于java - 为什么无法解码 Base64 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30540505/