首页 > 解决方案 > C++ 实现代码中的字符串不应出现在输出二进制文件中。怎么修

问题描述

我没有使用 -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','\0'};
  static char middle2[] = {'s','e','c','r', 'e','t','2','\0'};
  static char endbit[] = {'s','e','c','r', 'e','t','3','\0'};

  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 prog

我想隐藏的字符串仍在编中。

我怎样才能隐藏这些字符串?

标签: c++makefileg++

解决方案


要跟进上述评论,无法使用任何标准编译器或链接器工具隐藏这些字符串。你必须自己实现这个。

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

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


推荐阅读