Introduction


The example bash shell program below shows how to encode and decode a string using the Base64 algorithm. Base64 encoding is used to convert binary data into a text-like format to be transported in environments that handle only text safely. For example, encoding UID's for use in HTTP URL's or to encode encryption keys to make them safely portable through e-mail, display them in HTML pages and use them with copy and paste.

To simplify our life we use the base64 command, provided with the GNU coreutils package in Linux. base64 manual.

#!/bin/bash
# ###################################################################### #
# file:        base64_stringencode.sh v1.0                               #
# purpose:     tests encoding/decoding strings with base64               #
# author:      02/23/2009 Frank4DD                                       #
#                                                                        #
# This program encodes and decodes a sample string with base64 format.   #
# ########################################################################

mysrc='My bonnie is over the          '
myb64=""
mydst=""

myb64=`echo "$mysrc"|base64`

printf "The string\n[$mysrc]\nencodes into base64 as:\n[$myb64]\n"
echo

mydst=`echo $myb64 | base64 -d`

printf "The string\n[$myb64]\ndecodes from base64 as:\n[$mydst]\n"

exit 0;

A run of this test program returns the following output:

# ./base64_stringencode.sh
The string
[My bonnie is over the          ] 
encodes into base64 as:
[TXkgYm9ubmllIGlzIG92ZXIgdGhlICAgICAgICAgIA==]

The string
[TXkgYm9ubmllIGlzIG92ZXIgdGhlICAgICAgICAgIA==]
decodes from base64 as:
[My bonnie is over the          ]

Sample Code:

See Also: