使用c++破解私人数据
Hacking private data using c++
澄清:这个问题最初来自我想到的一个挑战,与实际系统的编程无关
假设我有一个类,我知道它的体系结构,我不能改变,我不想继承它,但我确实想访问它的私有数据和函数。我该怎么做?
假设我的课看起来像这样:
class A {
public:
int v = 89;
private:
int a = 5;
virtual void function(int a, int b) {
cout << a << " " << b << endl;
}
};
不久前在这个博客上偶然发现了一个巧妙的模板技巧:http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html
不要在任何生产代码中使用它,这只是一个教育性的例子!!!
它基本上利用了在模板初始化的某些部分被忽略的"私有">
template<typename Tag>
struct result {
/* export it ... */
typedef typename Tag::type type;
static type ptr;
};
template<typename Tag>
typename result<Tag>::type result<Tag>::ptr;
template<typename Tag, typename Tag::type p>
struct rob : result<Tag> {
/* fill it ... */
struct filler {
filler() { result<Tag>::ptr = p; }
};
static filler filler_obj;
};
template<typename Tag, typename Tag::type p>
typename rob<Tag, p>::filler rob<Tag, p>::filler_obj;
用法:采用以下结构:
struct A {
private:
void f() {
std::cout << "proof!" << std::endl;
}
};
创建你的"强盗">
struct Af { typedef void(A::*type)(); };
template class rob<Af, &A::f>;
使用它:
int main()
{
A a;
(a.*result<Af>::ptr)();
return 0;
}
如果只允许修改头文件,那么风险较小的破解方法是使函数/类成为类的friend
。
// Add
class HackA;
class A {
public:
// Add
friend class HackA;
int v = 89;
private:
int a = 5;
virtual void function(int a, int b) {
cout << a << " " << b << endl;
}
};
现在你可以使用:
class HackA {
public:
int number(A const& a) { return a.v; }
int another_number(A const& a) { return a.a; }
void target_function(A& a, int number, int another_one)
{
a.function(number, another_one);
}
};
int main()
{
A a;
HackA hacker
cout << hacker.number(a) << " " << hacker.another_number(a) << endl;
hacker.target_function(a, 9, 3);
return 0;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 在c代码之间共享数据的最佳方式
- 链表,反向函数,数据结构
- 数据成员SFINAE的C++17测试:gcc vs clang
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何对点云数据进行排序
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 使用c++破解私人数据