I would like to write a bash script to decode a base64 string. For example I type decode QWxhZGRpbjpvcGVuIHNlc2FtZQ==
and it prints Aladdin:open sesame
and returns to the prompt.
So far I have tried a simple bash file containing python -m base64 -d $1
but this command expects a filename not a string. Is there another non-interactive command (not necessarily in a Python module) that I can run from the command line to achieve this, without having to install any extra packages? (Or if I do, something super-minimal.)
Just use the
base64
program from thecoreutils
package:Or, to include the newline character
output (includes newline):
openssl can also encode and decode base64
EDIT: An example where the base64 encoded string ends up on multiple lines:
Here you go!
Add the following to the bottom of your
~/.bashrc
file:Now, open a new Terminal and run the command.
This will do exactly what you asked for in your question.
With your original dependencies it is possible to do this with a minor modification to your original script:
If you don't pass a file name, that python module reads from the standard input. To pipe the first parameter into it you can use
echo $1 |
.I did comment base64 command line in http://wiki.opensslfoundation.com/index.php?title=Command_Line_Utilities. So I issue a Warning when using openssl base64 decoding :
warning base64 line length is limited to 64 characters by default in openssl :
=> NOTHING !
to be able to decode a base64 line without line feed that exceed 64 characters use -A option :
This is anyway better to actualy split base64 result in 64 characters lines since -A option is BUGGY ( limit with long files ).
Using
perl
Or the same with
python
Just to add another way to do it:
I had a few moments of hair-pulling on this one because the
base64
Linux tool and also theopenssl
can decode, indeed. But I have this particular base64 encoded file that decodes to slightly wrong value. The few bytes do match, but then there is this presence ofEF BF BD EF BF BD
when I view inhexedit
viewer. And then the next sequence of bytes match again when compared to the correctly decoded expected output. These weird sequence of bytes got inserted in the in-betweens, sometime asEF BF BD
only.To resolve the matter, I have to look how the Java sender encodes it and then I created a small java base64 decoder. And now I can decoded to the expected value.
Here is the small snippet that does it: https://gist.github.com/typelogic/0567cdab6c15487c31496cb90006ff52