读(?)逃避字符

时间:2012-03-26 15:07:53

标签: c++

我正在尝试读取.php文件并替换hex'd字符。 php文件格式如下:

<?php ${"\x47\x4c\x4f\x42\x41\x4cS"}["\x6ana\x76\x79\x77\x70\x74\x62x"] ... ?>

问题在于它弄乱了转义字符(\“)

到目前为止我的代码:

while(i<=filelen)
{
    if(str[i]=='\\' && str[i+1]=='x' && (str[i+2]>=48 && str[i+2]<=57 || str[i+2]>=97 && str[i+2]<=122) )
    {
        string temp(str.substr(i,4));
        stringstream k;
        temp.erase(0,2);
        string temp2;
        temp2=hexToAscii(temp[0],temp[1]);
        output.append(temp2);
        i+=4;
    }
    else 
    {
        stringstream k;
        k<<str[i];
        output.append(k.str());
        i++;
    }
}

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这需要正则表达式!

答案 1 :(得分:0)

我无法重现你的问题。对于它的价值,这里是一个SSCCE(好吧,它不是那么短,因为我想保留你原来的代码,所以我不得不介绍一个hexToAscii函数等 - 你可能只是使用了strtoul

#include <iostream>
#include <sstream>
#include <string>

int hexToInt( char ch )
{
    if ( ch >= '0' && ch <= '9' ) {
        return ch - '0';
    }
    if ( ch >= 'a' && ch <= 'f' ) {
        return 10 + ch - 'a';
    }
    if ( ch >= 'A' && ch <= 'F' ) {
        return 10 + ch - 'A';
    }
    return -1;
}

std::string hexToAscii( char ch1, char ch2 )
{
    std::string result;
    result.push_back( static_cast<char>( hexToInt( ch1 ) * 16 + hexToInt( ch2 ) ) );
    return result;
}

void f( const std::string &str, const std::string::size_type filelen, std::string &output )
{
    std::string::size_type i = 0;
    using namespace std;
// ---- Verbatim copy starts
while(i<=filelen)
{
    if(str[i]=='\\' && str[i+1]=='x' && (str[i+2]>=48 && str[i+2]<=57 || str[i+2]>=97 && str[i+2]<=122) )
    {
        string temp(str.substr(i,4));
        stringstream k;
        temp.erase(0,2);
        string temp2;
        temp2=hexToAscii(temp[0],temp[1]);
        output.append(temp2);
        i+=4;
    }
    else 
    {
        stringstream k;
        k<<str[i];
        output.append(k.str());
        i++;
    }
}
// --- Verbatim copy ends
}

int main()
{
    //std::string input = "<?php ${\"\\x47\\x4c\\x4f\\x42\\x41\\x4cS\"}[\"\\x6ana\\x76\\x79\\x77\\x70\\x74\\x62x\"] ... ?>";
    std::string input = "${${\"\\x47\\x4cO\\x42A\\x4c\\x53\"}[\"\\x79\\x6b\\x6ehl\\x68r\\x70\\x77\\x66vj\"]}=\"<img \\x73\\x72c\\x3d\\x22\".e_PLUGIN.\"\\x72\\x65\\x63\\x6f\\x72\\x64s\\x2f\\x69\\x6d\\x61\\x67es\\x2ff\\x6c\\x61\\x67\\x73/\".getdemo_usercountry(${${\"\\x47L\\x4fB\\x41L\\x53\"}[\"f\\x79c\\x79r\\x79\\x63\\x65\\x75\"]}).\".\\x67\\x69\\x66\\x22\\x20bor\\x64er\\x3d\\x220\\\" \\x61\\x6c\\x74=\\\"\\x22 /\\x3e\\x20<a\\x20\\x68\\x72\\x65f=\\\"\".e_BASE.\"\\x75\\x73er\\x2eph\\x70?\\x69d\\x2e\".${${\"\\x47L\\x4fB\\x41\\x4c\\x53\"}[\"fy\\x63\\x79r\\x79\\x63\\x65\\x75\"]}.\"\\\">\".${${\"\\x47\\x4c\\x4fB\\x41\\x4c\\x53\"}[\"\\x64\\x66\\x76lt\\x79v\\x68h\\x68y\"]}[\"user_n\\x61me\"].\"\\x3c\\x2fa\\x3e\";";
    std::string result;
    f( input, input.size(), result );
    std::cout << "input: " << input << std::endl;
    std::cout << "output: " << result << std::endl;
}