Introduction


The example Perl 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 encode_base64() and decode_base64() functions which are provided with the MIME::Base64 Perl module.

#!/usr/bin/perl -w
# ###################################################################### #
# file:        base64_stringencode.pl 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.   #
# ########################################################################
use MIME::Base64;

$mysrc = "My bonnie is over the          ";
$myb64 = "";
$mydst = "";

$myb64 = encode_base64($mysrc);
chomp $myb64;

printf("The string\n[%s]\nencodes into base64 as:\n[%s]\n", $mysrc, $myb64);
printf("\n");

$mydst = decode_base64($myb64);
printf("The string\n[%s]\ndecodes from base64 as:\n[%s]\n", $myb64, $mydst);

exit 0;

A run of this test program returns the following output:

# ./base64_stringencode.pl
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: