Base64 Encoding in Perl

Perl provides built-in support for base64 encoding/decoding through the MIME::Base64 module.

use strict;
use warnings;
use MIME::Base64;

This syntax imports the MIME::Base64 module, which provides functions for base64 encoding and decoding.

my $data = "abc123!?\$*&()'-=\@~";

Here’s the string we’ll encode/decode.

# Standard base64 encoding
my $sEnc = encode_base64($data);
print $sEnc;

# Decoding
my $sDec = decode_base64($sEnc);
print $sDec, "\n\n";

Perl supports standard base64 encoding/decoding through the encode_base64 and decode_base64 functions. The encoder takes a string as input and returns the encoded string. The decoder does the reverse.

# URL-safe base64 encoding
my $uEnc = encode_base64($data, '');
$uEnc =~ tr/+\//-_/;
print $uEnc, "\n";

# URL-safe decoding
$uEnc =~ tr/-_/+\//;
my $uDec = decode_base64($uEnc);
print $uDec, "\n";

For URL-safe base64 encoding, we first encode normally, then replace ‘+’ with ‘-’ and ‘/’ with ‘_’. For decoding, we reverse this process before using the standard decoder.

When you run this Perl script, you’ll see output similar to the following:

$ perl base64_encoding.pl
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing + vs -) but they both decode to the original string as desired.

In Perl, error handling for decoding is typically done by checking if the decoded string is defined. If the input is not valid base64, the decode function will return undef.