在PHP中编码base64和在Java中解码base64的问题

问题描述 投票:0回答:5

使用 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 encoding character-encoding decode string-decoding
5个回答
2
投票

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


1
投票
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”,但编码错误。


1
投票

试试这个,它对我来说效果很好(但是我正在解码文件):

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"));
  }
}

请注意,您将需要额外的库:


0
投票

首先,您使用的代码不应编译,它在

"UTF-8
之后缺少结束引号。

是的,按照格式,

"gACA"
是一个有效的
base64
字符串,但它不会解码为任何有意义的 UTF-8 文本。我想你使用了错误的编码,或者以某种方式弄乱了字符串......


0
投票

RFC 4648 定义了two 字母表。

  1. PHP 使用 Base 64 编码
  2. Java 使用 Base 64 编码以及 URL 和文件名安全字母表

它们非常接近,但不完全相同。在 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));
}
© www.soinside.com 2019 - 2024. All rights reserved.