#! perl -w
# Network Forensics Puzzle Contest #2
# Alan Tu <alantu@as2.info>
# October 11, 2009

# base64d.pl
# Usage: base64d.pl [-f] [-d] argument
# Argument: a Base64 string to decode
# If -f is specified, argument is a filename containing Base64-encoded text to decode
# If -d is specified, the length and MD5 hash of the decoded data will be printed to STDERR
# The decoded output will be printed to STDOUT, use redirection to print to a file.

use strict;
use MIME::Base64;
use Digest::MD5;
use Getopt::Std;

our($opt_f, $opt_d);
getopts("fd");
die "Usage: $0 [-d] [-f file] | [encoded_base64]\n" unless @ARGV == 1;

my $data;
if ($opt_f) # argument is a file of Base64 data to decode
{
    die "File $ARGV[0] not found\n" unless -f $ARGV[0];
    local $/ = undef;
    open(IN, $ARGV[0]);
    $data = <IN>;
    close(IN);
}
else # argument is a string to decode
{
    $data = $ARGV[0];
}

$data = decode_base64($data);
binmode(STDOUT); # send binary to STDOUT
print $data;

if ($opt_d) # print length and MD5 of output to STDERR
{
    printf(STDERR "Length: %d\nMD5: %s\n", length($data), Digest::MD5::md5_hex($data));
}
