3

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Wow, that's embarrassing. I dove straight into messing with binmode() and didn't even see the chomp.
Also, you'll find unpack('H*', $binary_string) is much more efficient than split and printf '%02x'.
made a change#!/usr/bin/perl binmode(STDIN); while(<STDIN>) { #print $_; push(@bytes,$_); } foreach (@bytes) { printf "%02lx", ord $_; }
With the code change to binmod + removing chomp the stream is breaking
Verified chomp is removing the 0a from the encoding stream however I need to insert the following charachters '\x' per hex set eg 0d0d0a24 would be \x0d\x0d\x0a\x24 any suggestions how to do this would be appreciated.
|
1
#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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.