Atul Soman
Atul Soman

Reputation: 4720

Is it ok to remove newline in Base64 encoding

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.

Upvotes: 62

Views: 85514

Answers (5)

Marco Servetto
Marco Servetto

Reputation: 744

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...

Upvotes: 0

Sujeet
Sujeet

Reputation: 576

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.

Upvotes: 8

aeliton
aeliton

Reputation: 361

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.

Upvotes: 14

Roland Illig
Roland Illig

Reputation: 41676

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.

Upvotes: 63

Karthik
Karthik

Reputation: 1023

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.

Upvotes: -3

Related Questions