Is it ok to remove newline in Base64 encoding

JavaBase64

Java Problem Overview


My java application use base64 encoding which puts a new line (\n) after every 76 character. I need to put this encoded string in a properties file and the newline breaks the functionality.

When I do a encodedString.replaceAll("\n", ""); things are working fine, but I just want to make sure that this is expected and I am not introducing a hidden issue.

Java Solutions


Solution 1 - Java

Breaking a base64 encoded string into multiple lines has been necessary for many old programs that couldn't handle long lines. Programs written in Java can usually handle long lines since they don't need to do the memory management themselves. As long as your lines are shorter than 64 million characters there should be no problem.

And since you don't need the newlines, you shouldn't generate them at all, if possible.

Solution 2 - Java

Some of the Base64 encoders append EOL characters like CRLF ('\r\n') to the encoded strings. You can use Base64.encodeBase64URLSafe to get rid of them:

> Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The url-safe variation emits - and _ instead of + and / characters. Note: no padding is added.

Solution 3 - Java

You just need to Use Base64 encoding in following way

Base64.encodeBase64String("Your data to encrypt in base64")

Change above line with the followings

Base64.encodeBase64String("Your data to encrypt in base64",Base64.NO_WRAP)

This will solve your problem.

Solution 4 - Java

encodedString.replaceAll("\n", "");

DOES introduce a 'hidden issue' in the Java Mime encoder, and I just had to fight around it.

The lines are separated by "\r\n", not just "\n", so your replace leaves the "\r" in places, and those are ignored by most, but not all programs. For example, I was using the GitHub API where I had to generate JSON containing the base42-mime encoding for a file, and I was simply adding (") before and after a encodedString.replaceAll("\n", "") string... well.. it did not work because of the leftover \r...

Solution 5 - Java

It should not be an issue since many decoders are able to decode the encoded text without the newline delimiter. Safest option is to do the decoding yourself and verify it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAtul SomanView Question on Stackoverflow
Solution 1 - JavaRoland IlligView Answer on Stackoverflow
Solution 2 - JavaaelitonView Answer on Stackoverflow
Solution 3 - JavaSujeetView Answer on Stackoverflow
Solution 4 - JavaMarco ServettoView Answer on Stackoverflow
Solution 5 - JavaKarthikView Answer on Stackoverflow