简体   繁体   English

Perl将二进制流转换为十六进制

[英]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. 我遇到的问题是当我有一个Perl脚本通过STDIN读取数据(PE可执行文件)并且流包含行终止符“0A”时,转换为十六进制错过了它。 Then when I convert the hex data back it is corrupted (missing 0A in the hex format). 然后,当我将十六进制数据转换回来时,它已损坏(以十六进制格式丢失0A)。 So how can I detect the "windows" version of line feed "0A" in Perl? 那么如何在Perl中检测换行符“0A”的“windows”版本呢?

Note: Linux OS (Perl) is reading a Windows PE 注意:Linux OS(Perl)正在读取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

In your loop, you are running chomp on each input line. 在循环中,您在每个输入行上运行chomp 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. 有可能这是0x0a ,这就是值的来源。 Try removing chomp($line) from your loop. 尝试从循环中删除chomp($line)

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. 您应该查看较低级别的read功能,该功能允许您从文件中读取一个字节块,而无需关心这些字节是什么。 You can then process your data in blocks instead of lines. 然后,您可以使用块而不是行来处理数据。

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM