ekronnenburg
ekronnenburg

Reputation: 31

Perl converting binary stream to hex

The problem I am having is when I have a Perl script reading data (PE Executable) via STDIN and the stream contains a line terminator "0A" the conversion to hex misses it. Then when I convert the hex data back it is corrupted (missing 0A in the hex format). So how can I detect the "windows" version of line feed "0A" in Perl?

Note: Linux OS (Perl) is reading a Windows PE

!usr/bin/perl

while($line = <STDIN>)
{
    chomp($line);
    @bytes = split //, $line;
    foreach (@bytes)
    {
        printf "%02lx", ord $_;
    }
}

Usage example:

[root@mybox test]# cat test.exe | perl encoder.pl > output

Upvotes: 3

Views: 9098

Answers (2)

ph1g
ph1g

Reputation: 81

#With split
cat magic.exe | perl -e 'print join("", map { sprintf("\\x%02x", ord($_)) } split(//, join("", <STDIN>)))' > hex_encoded_binary

#With pack
cat magic.exe| perl -e 'print join("", map { "\\x" . $_ } unpack("H*", join("", <STDIN>)) =~ /.{2}/gs)' > hex_encoded_binary

Upvotes: 1

Eric Strom
Eric Strom

Reputation: 40152

In your loop, you are running chomp on each input line. This is removing whatever value is currently in $/ from the end of your line. Chances are this is 0x0a, and that's where the value is going. Try removing chomp($line) from your loop.

In general, using line oriented reading doesn't make sense for binary files that are themselves not line oriented. You should take a look at the lower level read function which allows you to read a block of bytes from the file without caring what those bytes are. You can then process your data in blocks instead of lines.

Upvotes: 6

Related Questions