尝试将String编码/解码为Base64时出错

我需要从字节数组进行Base64编码,而不是另一个字节数组。 但当我解码它时,我得到了例外。 这是代码

我正在尝试使用Base64编码将字节数组编码为字符串。 当我编码时,它似乎工作,但当我解码它会引发exception。 我究竟做错了什么?

import org.springframework.security.crypto.codec.Base64; byte[] bytes = new byte[]{1,2,3,4,5,6,7,8,9}; String stringToStore = Base64.encode(bytes).toString(); byte[] restoredBytes = Base64.decode(stringToStore.getBytes()); 

这是我得到的例外:

 org.springframework.security.crypto.codec.InvalidBase64CharacterException: Bad Base64 input character decimal 91 in array position 0 at org.springframework.security.crypto.codec.Base64.decode(Base64.java:625) at org.springframework.security.crypto.codec.Base64.decode(Base64.java:246) 

你能试试……

 byte[] bytes = new byte[]{1,2,3,4,5,6,7,8,9}; String stringToStore = new String(Base64.encode(bytes)); byte[] restoredBytes = Base64.decode(stringToStore.getBytes()); 

Base64.encode(bytes).toString()不返回您期望的String。

你应该用

 new String(Base64.encode(bytes)) 

正如iccthedral所暗示的那样。

如果您使用的是Android API 8+,则android.util有一个Base64助手类。

 String stringToStore = Base64.encodeToString(cipherText, Base64.DEFAULT); 
 String stringToStore = Base64.encode(bytes).toString(); 

那不是把字节变成字符串。 它是Java对象的字符串表示forms(例如, "[B@9a4d5c6" )。 您需要执行iccthedral建议并将字节提供给String类。

这对我有用:

  byte[] bytes = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; String stringToStore = Base64.encode(bytes); //System.out.println(stringToStore);//AQIDBAUGBwgJ byte[] restoredBytes = Base64.decode(stringToStore); //System.out.println(Arrays.toString(restoredBytes));//[1, 2, 3, 4, 5, 6, 7, 8, 9] 

我编辑了一下:

  • 不要在String上调用toString()encode(bytes)方法已经返回一个String (正如其他人所说,这可能是什么导致错误)
  • 为什么在不需要更多代码时转换为字节( Base64.decode(stringToStore.getBytes())

最初如果您使用此密码,则不建议将其转换为字符串。 要用作String,请遵循以下代码段


     byte [] bytes = new byte [] {1,2,3,4,5,6,7,8,9};
     String stringToStore = new String(Base64.encode(bytes),“UTF-8”);
     byte [] restoredBytes = Base64.decode(stringToStore.getBytes());

Base64.decode()似乎返回一个byte\[\] 。 调用toString()会给你一些数组的默认Java描述,就像“56AB0FC3 …”一样。 您需要自己进行转换。

同样,你对getBytes()调用并没有完全按照你的想法进行。

我从apache编解码器尝试了Base64,结果很好。

  import org.apache.commons.codec.binary.Base64; byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Base64 base64 = new Base64(); byte[] stringToStore = base64.encode(bytes); System.out.print(Arrays.toString(stringToStore));//[65, 81, 73, 68, 66, 65, 85, 71, 66, 119, 103, 74] byte[] restoredBytes = base64.decode(stringToStore); System.out.print(Arrays.toString(restoredBytes));//[1, 2, 3, 4, 5, 6, 7, 8, 9] 

要解码包含base64内容的字节数组,可以使用javax.xml.bind.DatatypeConverter 。 它工作得很好。 我用它来解码二进制类型的MongoDB值。

 String testString = "hi, I'm test string"; byte[] byteArrayBase64 = org.apache.commons.codec.digest.DigestUtils.md5(testString); String decoded = javax.xml.bind.DatatypeConverter.printBase64Binary(byteArrayBase64); assert testString.equals(decoded);