Does not use OO Encapsulation creates Security Ris

2019-08-22 09:44发布

问题:

This question maybe sounds some stupid, but i have the curiosity to know, if expose the fields of an object like publics, can create a security risk or a hole in my aplication that can be exploited by other persons?

public class AClass
{
    public int AProperty { get; set; }

    //Less Secure?
    public int APublicField;
}

Thanks

回答1:

Access modifiers (public, private, protected) are simply a mechanism to allow different levels of encapsulation for those with source access. You should employ them with OOP best practices to make your logic easy to maintain. They have absolutely nothing to do with the security of your application.

In C# you can use RTTI to reflect on private data just as easily as public. Thanks to the CLR and binary compatibility guarantees of C# you can even do this on external binaries from within your own. Even if you couldn't use reflection, an attacker can use a dissasembler and inspect the code as intermediate language. You may want to read this post.

An astute attacker familiar with the platform could even look for clues on how to reverse engineer your application running kernel level debuggers such as softICE.

You could always try to use some form of security through obscurity by encapsulating your logic in an attempt to make the execution less obvious, but obviously if someone is persistant enough they will find a way.

The best bet for security is to do your research and look for well used libraries both commercial and open source. The more exposure there is in cryptography the better as library developers and white hats can collaborate to fix exploits as they are discovered.



回答2:

The two "fields" in your snippet are essentially equivalent. The first one is simply an auto-property. So, neither is more or less "secure" than the other.



回答3:

In fact, the setters and getters are just a historical best practice of the OOP.

Both of the solutions that you exposed don't respect the encapsulation, because when you change the name or the type of an attribute you must change it in all the classes where it's used.

However, one advantage of the public attribute is that you get less code, which helps to understand and maintain the code easily.



标签: c# security oop