Perl Implementation of Base64URL Encoding

This section provides a tutorial example on how to perform Base64URL encoding on binary files using my own implementation in Perl.

Unfortunately, Perl does not provide any default implementation of Base64URL encoding. So we have to do it ourself.

Here is a sample program that allows you to perform Base64URL encoding/decoding and other variations.

# Base64_Tool.pl
# Copyright (c) 2010 HerongYang.com. All Rights Reserved.

  use MIME::Base64;

  my $count = scalar(@ARGV);
  if ($count<4) {
    print("Usage:\n");
    print("perl Base64_Tool.pl mode standard input output\n");
    exit;
  }
  my ($mode, $standard, $inputFile, $outputFile) = @ARGV;
   
  $size = -s $inputFile;
  open(IN, "< $inputFile");
  binmode(IN);
  read(IN, $inputBytes, $size);

  $outputBytes = "";
  if ($mode eq "decode") {
    if ($standard=="url") {
      $inputBytes =~ s/-/+/sg;
      $inputBytes =~ s/_/\//sg;
    }
    $outputBytes = decode_base64($inputBytes);
  } else {
    $outputBytes = encode_base64($inputBytes);
    if ($standard eq "mime") {
    } elsif ($standard eq "url") {
      $outputBytes =~ s/\r|\n//sg;
      $outputBytes =~ s/\+/-/sg;
      $outputBytes =~ s/\//_/sg;
      $outputBytes =~ s/=//sg;
    } else {
      $outputBytes =~ s/\r|\n//sg;
    }
  }
  print($outputBytes."\n");
  
  open(OUT, "> $outputFile");
  binmode(OUT);
  print(OUT $outputBytes);  

Let's try it with different test cases:

herong$ perl Base64_Tool.pl encode url A.txt encoded.txt 
QQ

herong$ perl Base64_Tool.pl decode url encoded.txt decoded.txt   
A

herong$ perl Base64_Tool.pl encode url lazy_dog.txt encoded.txt
VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4=

herong$ perl Base64_Tool.pl decode url encoded.txt decoded.txt   
The quick brown fox jumps over the lazy dog.
  
herong$ perl Base64_Tool.pl encode url url.txt encoded.txt 
aS5odG0_NjQ-NjM

herong$ perl Base64_Tool.pl decode url encoded.txt decoded.txt   
i.htm?64>63

herong$ perl Base64_Tool.pl encode standard url.txt encoded.txt 
aS5odG0/NjQ+NjM=

herong$ php Base64_Tool.php decode standard encoded.txt decoded.txt   
i.htm?64>63

herong$ php Base64_Tool.php encode url icon.png encoded.txt 
iVBORw0KGgoAAAANSUhEUgAAABgAAAAY ... HwXgCfzQYOFCEQYGAAAAAElFTkSuQmCC

herong$ php Base64_Tool.php decode url encoded.txt decoded.txt   
?PNG... 

As you can see, my implementation of Base64URL in Perl works as expected.

Table of Contents

 About This Book

 Base64 Encoding

 Base64 Encoding and Decoding Tools

Base64URL - URL Safe Base64 Encoding

 Base64URL Encoding Algorithm

 Java Built-In Implementation of Base64URL

 Python Built-In Implementation of Base64URL

 PHP Implementation of Base64URL Encoding

Perl Implementation of Base64URL Encoding

 Base32 Encoding

 URL Encoding, URI Encoding, or Percent Encoding

 UUEncode Encoding

 References

 Full Version in PDF/EPUB