C++实现代码中的字符串不应存在于输出二进制文件中.如何解决

strings in C++ implementation code should not be present in output binary. How to fix

本文关键字:输出 二进制文件 何解决 解决 于输出 代码 实现 字符串 存在 C++      更新时间:2023-10-16

我没有使用 -g 编译器选项,但我仍然在我的可执行文件中很容易看到字符串。 例如,通过使用字符串程序。

这是我的代码:

测试.hpp:

#ifndef TEST_HPP_
#define TEST_HPP_
#include <string>
namespace ns1 {
class Test
{
public:
  std::string Get(const std::string& root);
private:
  void append_other_stuff(std::string& s);
};
} // namespace ns1
#endif // TEST_HPP_

测试.cpp:

#include "test.hpp"
static const char* privatePart = "_hideme_";
namespace ns1 {
std::string Test::Get(const std::string& root) {
  std::string result = root + "_fixed_" + privatePart;
  append_other_stuff(result);
  return result;   
}
void Test::append_other_stuff(std::string& s) {
  // all these string must be hidden
  static char middle1[] = {'s','e','c','r', 'e','t','1',''};
  static char middle2[] = {'s','e','c','r', 'e','t','2',''};
  static char endbit[] = {'s','e','c','r', 'e','t','3',''};
  s += middle1;
  s += middle2;
  s += endbit;
}
}

主.cpp:

#include "test.hpp"
#include <iostream>
using namespace std;
int main() {
  ns1::Test t1;
  cout << t1.Get("123") << endl;
}

制作文件:

CXX = g++
CXXFLAGS = -Wall -std=c++11

main.o: main.cpp
    $(CXX) $(CXXFLAGS) -c main.cpp
test.o: test.cpp test.hpp
    $(CXX) $(CXXFLAGS) -c test.cpp
prog: main.o test.o
    $(CXX) $(CXXFLAGS) main.o test.o -o prog

使用字符串的输出(缩短(:

字符串程序

_hideme_
_fixed_
;*3$"
zPLR
secret1
secret2
secret3

即使我运行 strip 命令:

条带 -s -g 程序

我要隐藏的字符串仍在程序中。

如何隐藏这些字符串?

为了跟进上面的评论,无法使用任何标准编译器或链接器工具隐藏这些字符串。 您必须自己实现这一点。

没有说你为什么要这样做,所以我犹豫是否提供如何做的建议。 请注意,任何拥有您的程序的人都可以自己解码此字符串,如果他们愿意,无论您经历了多少混淆:您只会隐藏字符串以防止随意调查。 没有办法安全地在程序中保存机密,除非它需要一些外部输入来解码。 因此,您绝对不应该使用这些方法在您的程序中存储密码或任何其他类型的秘密。

有了这个警告,如果这是你唯一的目标,有一些简单的方法可以防止通过strings显示内容:例如,您可以将字符串存储在一个静态的整数数组中,每个字符一个,然后在运行时将其转换回字符串。