Java 可以删除 Base64 编码中的换行符吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19952621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it ok to remove newline in Base64 encoding
提问by Atul Soman
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.
我的 java 应用程序使用 base64 编码,它\n
在每 76 个字符后放置一个新行 ( )。我需要将此编码字符串放入属性文件中,换行符会破坏功能。
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.
当我做某事时encodedString.replaceAll("\n", "");
工作正常,但我只想确保这是预期的,并且我不会引入隐藏的问题。
采纳答案by Roland Illig
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.
许多无法处理长行的旧程序需要将 base64 编码的字符串分成多行。用 Java 编写的程序通常可以处理长行,因为它们不需要自己进行内存管理。只要您的行少于 6400 万个字符,就没有问题。
And since you don't need the newlines, you shouldn't generate them at all, if possible.
并且由于您不需要换行符,因此如果可能,您根本不应该生成它们。
回答by Karthik
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.
这应该不是问题,因为许多解码器能够在没有换行符的情况下解码编码文本。最安全的选择是自己进行解码并验证。
回答by aeliton
Some of the Base64 encoders append EOL characters like CRLF ('\r\n') to the encoded strings. You can use Base64.encodeBase64URLSafeto get rid of them:
一些 Base64 编码器将 EOL 字符(如 CRLF ('\r\n'))附加到编码字符串。您可以使用Base64.encodeBase64URLSafe来摆脱它们:
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.
使用 base64 算法的 URL 安全变体对二进制数据进行编码,但不会分块输出。url-safe 变体发出 - 和 _ 而不是 + 和 / 字符。注意:没有添加填充。