Base64: java.lang.IllegalArgumentException: Invalid character

I try to send a confirmation email after user registration. I am using the JavaMail library for this purpose and the Java 8 Base64 class.

I encode user emails as follows:

byte[] encodedEmail = Base64.getUrlEncoder().encode(user.getEmail().getBytes(StandardCharsets.UTF_8)); Multipart multipart = new MimeMultipart(); InternetHeaders headers = new InternetHeaders(); headers.addHeader("Content-type", "text/html; charset=UTF-8"); String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>"; MimeBodyPart link = new MimeBodyPart(headers, confirmLink.getBytes("UTF-8")); multipart.addBodyPart(link); 

where confirmationURL :

 private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID="; 

And then decode it in the ConfirmRegistrationCommand like this:

  String encryptedEmail = request.getParameter("ID"); String decodedEmail = new String(Base64.getUrlDecoder().decode(encryptedEmail), StandardCharsets.UTF_8); RepositoryFactory repositoryFactory = RepositoryFactory .getFactoryByName(FactoryType.MYSQL_REPOSITORY_FACTORY); UserRepository userRepository = repositoryFactory.getUserRepository(); User user = userRepository.find(decodedEmail); if (user.getEmail().equals(decodedEmail)) { user.setActiveStatus(true); return Path.WELCOME_PAGE; } else { return Path.ERROR_PAGE; } 

And when I try to decode:

 http://localhost:8080/project/controller?command=confirmRegistration&ID=[ B@6499375d 

I get java.lang.IllegalArgumentException: Illegal base64 character 5b .

I tried using a basic encoder / decoder (rather than URLs) without success.

SOLVE:

The problem is this: on the line:

  String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>"; 

I call toString in an array of bytes, so I have to do the following:

 String encodedEmail = new String(Base64.getEncoder().encode( user.getEmail().getBytes(StandardCharsets.UTF_8))); 

Thanks to Jon Skeet and ByteHamster .

+12
source share
5 answers

Your encrypted text [ B@6499375d . This is not Base64, something went wrong with the encoding . This decoding code looks good.

Use this code to convert byte [] to string before adding it to the URL:

 String encodedEmailString = new String(encodedEmail, "UTF-8"); // ... String confirmLink = "Complete your registration by clicking on following" + "\n<a href='" + confirmationURL + encodedEmailString + "'>link</a>"; 
+13
source

I ran into this error as my encoded image started with data:image/png;base64,iVBORw0...

This answer led me to a solution:

 String partSeparator = ","; if (data.contains(partSeparator) { String encodedImg = data.split(partSeparator)[1]; byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8)); Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg"); Files.write(destinationFile, decodedImg); } 
+8
source

Just use the code below to solve this problem:

 JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1]. replace('-', '+').replace('_', '/')))).readObject(); 

In the code above replace('-', '+').replace('_', '/') work was done. See https://jwt.io/js/jwt.js for more details. I understood the problem on the part of the code obtained from this link:

 function url_base64_decode(str) { var output = str.replace(/-/g, '+').replace(/_/g, '/'); switch (output.length % 4) { case 0: break; case 2: output += '=='; break; case 3: output += '='; break; default: throw 'Illegal base64url string!'; } var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js try{ return decodeURIComponent(escape(result)); } catch (err) { return result; } } 
+2
source

The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.

For the encryption utility that I am writing, I took the input string of ciphertext, and Base64 encoded it for transmission, and then canceled the process. The relevant parts are shown below. NOTE. The file.encoding property is ISO-8859-1 when invoked by the JVM, so it can also have a bearing.

 static String getBase64EncodedCipherText(String cipherText) { byte[] cText = cipherText.getBytes(); // return an ISO-8859-1 encoded String return Base64.getEncoder().encodeToString(cText); } static String getBase64DecodedCipherText(String encodedCipherText) throws IOException { return new String((Base64.getDecoder().decode(encodedCipherText))); } public static void main(String[] args) { try { String cText = getRawCipherText(null, "Hello World of Encryption..."); System.out.println("Text to encrypt/encode: Hello World of Encryption..."); // This output is a simple sanity check to display that the text // has indeed been converted to a cipher text which // is unreadable by all but the most intelligent of programmers. // It is absolutely inhuman of me to do such a thing, but I am a // rebel and cannot be trusted in any way. Please look away. System.out.println("RAW CIPHER TEXT: " + cText); cText = getBase64EncodedCipherText(cText); System.out.println("BASE64 ENCODED: " + cText); // There he goes again!! System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText)); System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText))); } catch (Exception e) { e.printStackTrace(); } } 

The result is as follows:

 Text to encrypt/encode: Hello World of Encryption... RAW CIPHER TEXT: q$; C l  <8  U   X[7l BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA== BASE64 DECODED: q$; C l  <8  U   X[7l`` DECODED CIPHER TEXT: Hello World of Encryption... 
+1
source

I got the same error, and the problem was that the line started with data:image/png;base64,...

The solution was:

 byte[] imgBytes = Base64.getMimeDecoder().decode(imgBase64.split(",") 
0
source

Source: https://habr.com/ru/post/982678/


All Articles