使用 base64 在 PHP 中编码的字符串“gACA”。现在我正在尝试使用base64 在java 中进行解码。但解码后得到荒谬的值。我试过这样:
public class DecodeString{
{
public static void main(String args[]){
String strEncode = "gACA"; //gACA is encoded string in PHP
byte byteEncode[] = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(strEncode );
System.out.println("Decoded String" + new String(k, "UTF-8"));
}
}
输出:
??
请帮帮我
Java内置了Base64编码器-解码器,不需要额外的库来解码:
byte[] data = javax.xml.bind.DatatypeConverter.parseBase64Binary("gACA");
for (byte b : data)
System.out.printf("%02x ", b);
输出:
80 00 80
3个字节,十六进制代码:
80 00 80
public static void main(String args[]) {
String strEncode = "gACA"; //gACA is encoded string in PHP
byte byteEncode[] = Base64.decode(strEncode);
String result = new String(byteEncode, "UTF-8");
char[] resultChar = result.toCharArray();
for(int i =0; i < resultChar.length; i++)
{
System.out.println((int)resultChar[i]);
}
System.out.println("Decoded String: " + result);
}
我怀疑这是一个编码问题。 关于 65533 的问题 � 在 C# 文本文件读取中 这篇文章建议第一个和最后一个字符是 \“。中间有一个字符 0。你的结果可能是“”或“0”,但编码错误。
试试这个,它对我来说效果很好(但是我正在解码文件):
Base64.decodeBase64(IOUtils.toByteArray(strEncode));
所以它看起来像这样:
public class DecodeString{
{
public static void main(String args[]){
String strEncode = "gACA"; //gACA is encoded string in PHP
byte[] byteEncode = Base64.decodeBase64(IOUtils.toByteArray(strEncode));
System.out.println("Decoded String" + new String(k, "UTF-8"));
}
}
请注意,您将需要额外的库:
首先,您使用的代码不应编译,它在
"UTF-8
之后缺少结束引号。
是的,按照格式,
"gACA"
是一个有效的 base64
字符串,但它不会解码为任何有意义的 UTF-8 文本。我想你使用了错误的编码,或者以某种方式弄乱了字符串......
RFC 4648 定义了two 字母表。
它们非常接近,但不完全相同。在 PHP 中:
const REPLACE_PAIRS = [
'-' => '+',
'_' => '/'
];
public static function base64FromUrlSafeToPHP($base64_url_encoded) {
return strtr($base64_url_encoded, self::REPLACE_PAIRS);
}
public static function base64FromPHPToUrlSafe($base64_encoded) {
return strtr($base64_encoded, array_flip(self::REPLACE_PAIRS));
}