![](/img/trans.png)
[英]How can I execute a jar file included in c++ with a Base64 string without write it on the HDD?
[英]C++: How to encode a std::string into base64 without losing NUL character
我正在努力啟動並運行其他人的代碼 。 該代碼用C ++編寫。 失敗的部分是將std :: string轉換為base64時:
std::string tmp = "\0";
tmp.append(strUserName);
tmp.append("\0");
tmp.append(strPassword);
tmp = base64_encode(tmp.c_str(), tmp.length());
其中base64是:
std::string base64_encode(char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
它使用“ tmp”字符串來調用服務器,並且必須在base64字符串中嵌入兩個NUL字符(在strUserName之前和strPassword之前)。 但是,由於代碼正在將tmp作為c_str()傳遞,因此NUL字符已被剝離。 有一個好的解決方案嗎? 謝謝。
更新,我想我應該補充一點,代碼中包括“ #include <asm/errno.h>
”,我用它搜索了一下,但沒有發現與macOS的兼容性,所以我只是將其注釋掉了。但我對此表示懷疑。 全面披露。
std::string tmp = "\\0";
和tmp.append("\\0");
不要在tmp
添加任何'\\0'
字符。 帶有const char*
的std::string::string
和std::string::append
的版本采用NUL終止的C樣式字符串,因此一旦看到NUL字符,它們就會停止。
要將NUL字符實際添加到字符串中,您需要使用構造函數並append
帶有const char*
長度的方法或帶有count和char
的版本的方法:
std::string tmp("\0", 1);
tmp.append(strUserName);
tmp.append("\0", 1);
tmp.append(strPassword);
tmp = base64_encode(tmp.c_str(), tmp.length());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.