#!/usr/local/bin/perl -ln

# base64 encoding and decoding in Perl
# © 1996 Roman Czyborra@cs.tu-berlin.de

# In 1993 Barrett@ee.und.ac.za published a perl package base64.pl that
# mapped base64 to uuencode characters (tr[A-Za-z0-9/+=][`!-_`]) and
# then went on to unpack("u","M".$&).  While this may be efficient, I
# find it awkward to compute the line length and not very transparent.
# I prefer the three-liners below resembling the direct base64
# encoding algorithm as described in RFC 1521 § 5.2.

encode:
{
    $_=unpack("B*",$_); s/$/0000/; s/.{6}/00$&/g;
    s/((.{8})*).*/pack("B*",$1)/e; tr[\0-\77][A-Za-z0-9+/];
    s/$/===/; s/((....)*).*/$1/; s/.{76}/$&\n/g;
}

print;

decode: 
{
    tr[A-Za-z0-9+/][]cd; tr[A-Za-z0-9+/][\0-\77];
    s/./unpack("xxa6",unpack("B8",$&))/ge;
    s/((.{8})*).*/pack("B*",$1)/e;
}

print;
