The security of running code in .NET revolves around the concept of Code Access Security (CAS). CAS determines the trustworthiness of an assembly based upon its origin and the characteristics of the assembly itself, such as its hash value. For example, code installed locally on the machine is more trusted than code downloaded from the Internet. The runtime will also validate an assembly’s metadata and type safety before that code is allowed to run.
There are many mechanisms that we can use to write secure code and protect data using the .NET Framework. In this chapter, we explore such topics as controlling access to types, encryption/decryption, randomizing numbers for use with encryption, securely storing data, and using programmatic and declarative security.
You have data in a string that you want to be able to encrypt and decrypt—perhaps a password or software key—which will be stored in some form, such as in a file or the registry. You want to keep this string a secret so that users cannot take this information from you.
Encrypting the string will help to prevent users from being able to read and decipher the information. The
CryptoString class shown in Example 11-1 contains two static methods to encrypt and decrypt a string and two static properties to retrieve the generated key and initialization vector (IV—a random number used as a starting point to encrypt data) after ...