So you need some crypto stuff (easy to use and ready for shipping) and don’t have enough time or interest in learning and writing all that crypto code?If this is your scenario, this article might be for you. I have seen lot of people asking how to use some of the common cryptographic primitives (encryption, hashing, signing, etc.). To help those people I have written these classes that contain all the named primitives and a bunch of handy functions to protect in-memory data as well as gather user credentials from UI and many others nice to have functions. It’s important to note that these classes are essentially wrappers to the methods found in the Cryptography namespace of the .NET Framework security classes. The real value added to this wrapper is basically all the implementation “Best Practices” gathered from several well-known sources as the ones listed at the end of this article.
Note: Text in read are updates to the original post.
Downloads
You can download the code with the cryptography classes and the “Test Harness Client” from
here
.
The example code is provided as source code that you can use "as is" or customize for your application.
Usage
One of the main goals of these classes is being very simple to use and understand. Here is the easiest function overload for encrypting a string.
// Use ProtectedData.Protect method (DPAPI) string cipherText = CryptoHelper.Encrypt( "InputData" ); |
As you probably wonder where the password or encryption key is. It happens that this overload uses the ProtectedData class that in turn calls a DPAPI (Data Protection API) function that do the final encryption. DPAPI is particularly useful in that it can eliminate the key management problem exposed to applications that use cryptography. This method return the encrypted data encoded in base64 in order to make things easier when you need to manipulates binary strings. Other methods like the ones that compute a hash, returns strings encoded in hexadecimal, the usual data encoding for these operations. There are many more overloads that operate with byte arrays as well. The CryptoHelper class provides methods for encryption and decryption, hashing operations, digital signature and verification, and random number generation. In the following table we have a brief summary of each class (this was extracted from the Reference help included in the download).
Class |
Description |
CryptoHelper |
Provides static methods that supply helper utilities for manipulating cryptographic primitives access. This class cannot be inherited. |
ProtectedData |
This class implement access to DPAPI library. |
ProtectedMemory |
Encrypts memory to protect sensitive information. (Only works in Windows XP and Windows 2003 or better) |
UICredentialsHelper |
This class provide access to a feture provided by Windows XP and Windows Server 2003 called "Stored User Names and Passwords" to associate a set of credentials with a single Windows user account, storing those credentials using the Data Protection API (DPAPI) (See ProtectedData class). This class cannot be inherited. |
Util |
Helper common methods. |
WinAccessHelper |
Provides static methods that supply helper methods for windows accounts authentication and authorization. |
CryptographicPermission |
This class is the custom permission implementation used to authorize cryptographic operations with restricted access. |
CryptographicPermissionAttribute |
Allows security actions for CryptographicPermission to be applied to code using declarative security. |
Making it “industry strength”It’s important to note that these classes are intended to be a shippable piece of code as well as easy to use and understand. Let’s see what features have this samples that makes them a “plug ‘n play” code. Here is a list of things that are already done for you inside each public method.· Parameter Checking and Error handling o Parameters are test for validity (null testing and range depending each case)o Try/finally blocks are used to release resource if something goes wrong. · Random salt and IV generation and storageo When deriving a key from a given password (see DerivedKey internal class), a random salt is created in order to mitigate dictionary attacks against the derived key.o The salt generated for the derived key from the user provided password is stored together with the encrypted data (the salt is not a secret) in order to later retrieval and use for decryption. Code Access Security NoteThe sample library (Cryptography.dll) provided is strong named and allow to be called from partially trusted callers. To call this library from partially trusted callers follow this steps:
- Run the TestNCryptoSecurityPolicy.msi file to install the sample Code Group and the "CryptographicPermission" permission set in order to build the sandbox environment.
- For testing purposes, you can ran the CryptoUtilitiesTestHarness.exe test application from an Intranet or Internet Zone changing the project OutputPath.
Intranet: OutputPath = \\MACHINENAME\C$\...\bin\Debug\ Internet: OutputPath = \\127.0.0.1\C$\...\bin\Debug\ (Complete the “...” with the rest of the path where your project resides.)
Future Enhancements
As always happens with coding, there is room for improvements and extensions. Here are a few features that I think it might be useful to have.· Streaming operations (Add some overloads with stream type parameters).· File Wiping (Erase files in a way that will be unlikely to restore)· Better support for asymmetric operations (X509 support, keys manipulation, etc.)· Additional Algorithms.If you need a better support for X509 Certificates you can found it in this two excellent free libraries. The Security Library from Mentalis (source code included) or with the WSE 2.0 that you can download it from here (sorry, no source code).
Feedback And Comments
Questions? Comments? Suggestions? What else can be done to make this sample classes more secure and useful ? Please, feel free to send me all your comments and suggestions. Recall that this code is completely free and without any license restrictions. Further Additional Info: Here are some useful links and my recommended books. - Code Access Security http://msdn.microsoft.com/msdnmag/issues/01/02/CAS/default.aspx - Strong Names: (Protecting the private key) http://msdn.microsoft.com/netframework/?pull=/library/en-us/dnnetsec/html/strongNames.asp http://msdn.microsoft.com/netframework/?pull=/library/en-us/dnnetsec/html/strongNames.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/THCMCh08.asp?frame=true#c08618429_008 - APTCA: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/THCMCh08.asp?frame=true#c08618429_005 Books: - Writing Secure Code, Second Edition by Michael Howard (Author), David C. LeBlanc http://www.amazon.com/exec/obidos/tg/detail/-/0735617228/104-1625630-5338364?v=glance#product-details - .NET Framework Security by Brian A. LaMacchia, Sebastian Lange, Matthew Lyons, Rudi Martin, Kevin T. Price http://www.amazon.com/exec/obidos/tg/detail/-/067232184X/ref=pd_sim_books_3/104-1625630-5338364?v=glance&s=books - Security Engineering: A Guide to Building Dependable Distributed Systems by Ross J. Anderson http://www.amazon.com/exec/obidos/tg/detail/-/0471389226/qid=1076345811//ref=sr_8_xs_ap_i1_xgl14/104-1625630-5338364?v=glance&s=books&n=507846 This posting is provided "AS IS" with no warranties, and confers no rights.