René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

hexdumper [Perl]

hexdumper.pm
package hexdumper;

use strict;
use warnings;

my $spaces='     ';

sub new {
  my $obj  = shift;
  my $self = {};

  $self -> {buf}      = "";
  $self -> {byte_cnt} = 0;
  $self -> {width}    = shift;

  return bless $self, $obj;
}

sub write {
  my $self = shift;
  my $bytes= shift;

  my $ret = "";

  if ($self->{byte_cnt} == 0) {
    $ret .= sprintf("%6d:  ", $self->{byte_cnt});
  }

  for (my $pos = 0; $pos < length($bytes); $pos++) {
    my $cur_byte = substr($bytes, $pos, 1);

    $self->{byte_cnt} ++;

    if (ord($cur_byte) >= 32 and ord($cur_byte) <= 126) { # printable
      $self->{buf} .= $cur_byte;
    }
    else {
      $self->{buf} .= ' ';
    }

    $ret .= sprintf("%02x ", ord($cur_byte));

    if (length($self->{buf}) == $self->{width}) {
       $ret .= $spaces . $self->{buf} . "\n";
       $ret .= sprintf("%6d:  ", $self->{byte_cnt});
       $self->{buf} = "";
    }
  }

  return $ret;
}

sub end {
  my $self = shift;

  return "   " x ($self->{width} - $self->{byte_cnt} % $self->{width}) .
         $spaces .  $self->{buf};
}

1;

Using the package

use strict;
use warnings;

use hexdumper;

my $out="";

my $hexdumper = new hexdumper(16);

$out .= $hexdumper -> write(<<END);
first some ascii text is written. This
text is then followed by fourty
random bytes.
END

for (my $i=0; $i<40; $i++) {
  $out .= $hexdumper -> write(chr(int(rand()*256)));
}
  
$out .= $hexdumper -> write("Then, ");
$out .= $hexdumper -> write("more text is ");
$out .= $hexdumper -> write("appended.");

$out .= $hexdumper -> end;

print $out;
The script produces:
$ perl usehexdumper.pl.raw
     0:  66 69 72 73 74 20 73 6f 6d 65 20 61 73 63 69 69      first some ascii
    16:  20 74 65 78 74 20 69 73 20 77 72 69 74 74 65 6e       text is written
    32:  2e 20 54 68 69 73 0a 74 65 78 74 20 69 73 20 74      . This text is t
    48:  68 65 6e 20 66 6f 6c 6c 6f 77 65 64 20 62 79 20      hen followed by
    64:  66 6f 75 72 74 79 0a 72 61 6e 64 6f 6d 20 62 79      fourty random by
    80:  74 65 73 2e 0a fc 9b 51 c6 78 f6 aa e8 84 a9 66      tes.   Q x     f
    96:  36 26 8a 66 45 c5 0d 47 27 4f 78 dd 31 be d4 d0      6& fE  G'Ox 1
   112:  19 8f 26 da 1b d8 43 bc 1e 07 de 45 84 54 68 65        &   C    E The
   128:  6e 2c 20 6d 6f 72 65 20 74 65 78 74 20 69 73 20      n, more text is
   144:  61 70 70 65 6e 64 65 64 2e                           appended.

Links

This package is used in On a breakable Oracle to demonstrate a critical security bug.