我需要从字节数组进行Base64编码,而不是另一个字节数组.但当我解码它时,我得到例外.这是代码
我正在尝试使用Base64编码将字节数组编码为字符串.当我编码时,它似乎工作,但当我解码它会引发异常.我究竟做错了什么?
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());
Run Code Online (Sandbox Code Playgroud)
这是我得到的例外:
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)
Run Code Online (Sandbox Code Playgroud)
nul*_*ent 17
你能试试......
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());
Run Code Online (Sandbox Code Playgroud)
Base64.encode(bytes).toString() 不返回您期望的字符串。
你应该用
new String(Base64.encode(bytes))
Run Code Online (Sandbox Code Playgroud)
如iccthedral所建议。
这对我有用:
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]
Run Code Online (Sandbox Code Playgroud)
我稍微编辑了一下:
toString()打电话String。encode(bytes)方法已经返回 a String(正如其他人所指出的,调用这可能是导致错误的原因)Base64.decode(stringToStore.getBytes()))| 归档时间: |
|
| 查看次数: |
67805 次 |
| 最近记录: |