This note is intended to help you on how to prevent third-party applications from accesing the features developed by us. This could be useful in the following cases:
We have a class that encrypts and decrypts files (which would prevent a third party to add our DLL as a reference to access these methods).
- Access to databases.
- Password recovery.
- Etc ...
Generally, these points have the following specifications:
They must be public for all the assembly / executable.
It should not be possible to use these features just adding them as a reference.
As the solution, .Net Framework provides the internal keyword to make public methods, variables or classes but only within the assembly.
Although this can not be visible from "outside", there should be a way of declaring what are these projects likely to access the internals of this DLL / EXE.
Solution: Let's suppose we want to make visible all the internals of Business.dll to Business.Test.dll since we will develop unit tests on the first one. It should take the following steps:
- Sign the Business assembly doing right click the
Project --> Properties --> Signing --> tick the "Sign the assembly" -->
In the drop-down combo select "New" and type in the signature file in our case can be "MySnk " will generate a file with a hex code, then you should always use this file to sign the assemblies of the company.
Sign the assembly Business.Test, but this time with the new file we created in the previous step. (MySnk.snk)
Now, both assemblies are signed with what is known as "Strong Sign". Keep the .snk file only in the development environment, because distributing it to any third party that could use it to sign your assemblies and lose the benefits of all the work that has being done.
By signing with this file both assemblies are identical public key that gives them the fact of signing with the same file MySnk.snk What is the public key like?
3.1 Open the DOS console Visual Studio and we are positioned in the directory where the assembly we want to obtain the public key.
3.2 We use the command sn-Tp
Business within the Properties folder is a file called AssemblyInfo.cs. Add the following line:
[assembly: InternalsVisibleTo("Business.Test, PublicKey=00240000048...a very long number ...a07191ad0")]
Thus we declare the assembly Business with its visible internals to a certain assembly (Business.Test in this case) containing the same public key. In this, the will only be used by Business.Test and no other.