Base64解码:无效输入。

69

在GNU/Linux上尝试解码base64文件时,我收到了“base64: invalid input”错误提示。

$ base64 test.zip | base64 -d > test2.zip
base64: invalid input
$ ll test*
-rw-r--r-- 1 user grp 152 19 11:41 test.zip
-rw-r--r-- 1 user grp  57 19 11:42 test2.zip

I tried dos2unix 命令,但没有帮助。
我的base64版本:
$ base64 --version
base64 (GNU coreutils) 5.97
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software.  You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.

Written by Simon Josefsson.

在我的系统中,解码是 -D,而不是 -d。在你的系统上,base64 --help 显示什么? - John Zwinck
1
请考虑升级;当前版本至少为8.20(来自2012年),可能仍有更新版本。 - Jonathan Leffler
那个版本是CentOS 5.x安装的版本,所以取决于谁控制环境,他可能没有选择的选项。 - Joe
是的,这是一个旧版本的Linux。Red Hat Enterprise Linux Server 5.3(Tikanga)于2009年1月20日发布。 - andyf
5个回答

118

那个版本默认不会解码带分隔符的行,但编码器默认会这样做。(更新的版本没有这个问题。)

一个解决方法:

base64 -w 0 foo.zip | base64 -d > foo2.zip

另一种方法:

base64 foo.zip | base64 -di > foo2.zip

-i选项代表(来自man页面):

-i, --ignore-garbage
       When decoding, ignore non-alphabet characters.
[...]
Decoding require compliant input by default, use --ignore-garbage to
attempt to recover from non-alphabet characters (such as newlines)

6
对我有用的只有另一种解决方案。即使没有换行符,"base64 -d" 仍然在抱怨。 - cdhowie
我输入了“-i”,但没有起作用。我输入了“--ignore-garbage”,它就可以工作了 :D - Quim Serra

9
甚至更简单的方法如下: base64 -di foo.zip > foo2.zip

13
谢谢Shawn,并欢迎来到StackOverflow。你的答案简洁明了!为了进一步提高它的质量,你可以考虑简要解释一下-di选项。 - Jeremy

4
如果您是在Mac上进行此操作,则您的base64版本可能无法处理忽略垃圾数据。如果您使用brew install coreutils安装,您将拥有gbase64实用程序,并可以按照Joe所述使用它。

除了 gbase64,macOS 还有其他的方法吗?我正在寻找一种在 macOS 和 Linux 上都能使用的方法。我的 Linux 命令目前是 echo ${ANDROID_KEYSTORE_TESTING} | base64 -di > file.keystore - Dimitri Kopriwa
有时你也会在 Linux 系统上找到 coreutils 的 g* 名称(我很确定以前见过)。这取决于是否使用 --program-prefix=g 编译,也许你有能力在你的系统上这样做。更多细节请参考:https://unix.stackexchange.com/a/478055/101165 - Micah Elliott

2

你也可以尝试使用

echo -n

抑制换行符,并用一个到三个等号字符填充输入长度,使其成为4的倍数

=

0
对我来说,我从Linux终端复制了base64输出到一个文件,在Windows(Sublime Text)的文件中粘贴并保存。但是base64 -d在运行时出现错误:base64:无效输入。通过查看输入文件,我发现该文件有 Windows行结尾符(CRLF),而原始的base64数据是在Linux中使用Unix行结尾符生成的。因此,我重新打开源base64文件,将行结尾符更改为Unix格式,并保存文件,解码过程顺利完成,没有任何问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接