Reflection brings great convenience to our programming, but we tend to ignore the other side of this double-edged sword (also sharp. By design, as long as you have the corresponding reflectionpermission, Reflection allows you to access all the classes (including nonpublic) in an assembly and allow you to access all the methods in a class, properties and fields (including nonpublic )!
In our actual work, many people think that private member is inaccessible under the object-oriented protection mechanism, therefore, if I do not allow others to access a member of mine, I just need to add private before it ...... But we do not know that the object-oriented protection mechanism in reflection is just a false one. Let's look at an example.
Imagine the following scenario:
I have an Assembly named seclib, which contains a public encryption method (encrypt) and a private decryption method (decrypt). My intention is to only allow others to use encrypt for encryption, the decrypt is called only by myself (because it is completely a pair of tightly coupled methods, it is natural to put them in an assembly ):
Public class seclib
{
Public static byte [] encrypt (string S)
{
}
Private Static string decrypt (byte [] D)
{
}
}
After a user obtains my seclib, a reflection tool such as reflector discovers the decrypt method in my seclib. Therefore, although he cannot directly call decrypt as follows:
// String S = seclib. decrypt (d );
But it can be achieved through reflection:
Type T = typeof (seclib );
Methodinfo MI = T. getmethod ("decrypt", bindingflags. Static | bindingflags. nonpublic );
String S = (string) MI. Invoke (null, new object [] {encrypteddata });
Download the complete exampleCode: Reflectiontrap.zip