Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

java - Error when trying to encode/decode String to Base64

I need to do Base64 encoding from byte array to stirng as opposed to another byte array. But when I decode it back I get exception. Here is the code

I'm trying to encode a byte array into a string using Base64 encoding. When I encode, it seems to work, but when I decode it throws an exception. What am I doing wrong?

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());

Here is the exception I'm getting:

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Could you try...

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()); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...