Potential threats brought by reflection

Source: Internet
Author: User
Tags decrypt
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.