所以我有这个函数XORes一个字符串,然后把它变成这样的格式:
\x55\x1\x53\x21...
但问题是该函数首先返回负值,但是我通过将它从CHAR转换为UCHAR来修复它,但是现在它开始给我的值太大而且编译器不允许我因为它而编译。有什么想法会发生这种情况吗?无法在网上找到任何相关信息。
__inline char* EncryptString(const char* String, const char* Key)
{
char* szEncrypted = new char[lstrlenA(String) + 1];
memcpy(szEncrypted, String, lstrlenA(String) + 1);
for (int32_t i = 0; i < lstrlenA(String); ++i)
szEncrypted[i] = String[i] ^ Key[i % (lstrlenA(Key))];
std::stringstream lpStream;
for (int32_t i = 0; i < lstrlenA(szEncrypted); ++i)
{
char cCharInd = szEncrypted[i];
UINT nCharNum = UINT(cCharInd);
lpStream << "\\x" << std::hex << nCharNum;
}
std::string sHexEscaped = lpStream.str();
lpStream.clear();
delete[] szEncrypted;
char* szReturn = new char[sHexEscaped.length() + 1];
memcpy(szReturn, sHexEscaped.c_str(), sHexEscaped.length() + 1);
return szReturn;
}
答案 0 :(得分:1)
问题是类型char
可以签名或取消签名(取决于编译器)。我认为以下代码可以帮助您:
const unsigned char uc = static_cast<unsigned char>( szEncrypted[i] );
const unsigned int code = uc;
lpStream << "\\x" << std::hex << code;
P.S。看起来你实际上不需要使用临时缓冲区szEncrypted。
<强>更新强>
我试图在下面的代码中演示这种加密是如何工作的(源文件编码是Windows-1251)。您还必须知道加密字符串可能包含\0
个字节,因此,要计算加密字符串的长度,您可能会使用以下内容:const char rawString[] = "\xf\x55\x0\x1e\x22\x98\x20\x1e\x2b\x4b\x12"; const int rawSize = sizeof( raw ) - 1;
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
string EncryptString( const char* String, const char* Key )
{
std::stringstream lpStream;
const int keyLength = strlen( Key );
for( int i = 0; String[i] != '\0'; i++ ) {
char ec = String[i] ^ Key[i % keyLength];
unsigned char uc = static_cast<unsigned char>( ec );
lpStream << "\\x" << std::hex << static_cast<unsigned int>( uc );
}
return lpStream.str();
}
void DecryptString( string& String, const char* Key )
{
const int keyLength = strlen( Key );
for( string::size_type i = 0; i < String.length(); i++ ) {
String[i] ^= Key[i % keyLength];
}
}
int main()
{
system( "ChCp 1251" );
const char* key = "Пётр";
cout << EncryptString( "Антон Тодуа", key ) << endl;
const char raw[] = "\xf\x55\x0\x1e\x22\x98\x20\x1e\x2b\x4b\x12";
string data( raw, sizeof( raw ) - 1 );
DecryptString( data, key );
cout << data << endl;
return 0;
}