#!/usr/bin/perl -w # encode2.pl - Don Yang (uguu.org) # # 09/06/08 use strict; use constant BASE => 90; # Encode block of bytes sub Encode($) { my ($input) = @_; my $output = ""; my $remainder = (length($input) % 4) ? (4 - (length($input) % 4)) : 0; foreach my $x (unpack 'V*', $input . "\0\0\0") { my $a = $x % BASE; my $b = ($x /= BASE) % BASE; my $c = ($x /= BASE) % BASE; my $d = ($x /= BASE) % BASE; my $e = $x / BASE; $output .= pack 'C*', $a + 33, $b + 33, $c + 33, $d + 33, $e + 33; } for(; $remainder > 0; $remainder--) { chop $output; } return $output; } # Decode block of bytes sub Decode($) { my ($input) = @_; my $input_length = length($input); my $remainder = (length($input) % 5) ? (5 - (length($input) % 5)) : 0; $input .= chr(33) x $remainder; my $output = ""; for(my $i = 0; $i < $input_length; $i += 5) { my ($e, $d, $c, $b, $a) = unpack 'C*', substr($input, $i, 5); my $x = (((($a - 33) * BASE + $b - 33) * BASE + $c - 33) * BASE + $d - 33) * BASE + $e - 33; $output .= pack 'V', $x; } for(; $remainder > 0; $remainder--) { chop $output; } return $output; } # Test Encode/Decode pairs sub Test() { die if( Decode(Encode("")) ne "" ); for(my $i = 0; $i < 8; $i++) { my $input = ""; for(my $j = 0; $j < 1024 * 1024 + $i; $j++) { $input .= chr(rand 256); } die if( Decode(Encode($input)) ne $input ); } } Test();