Encrypt and Decrypt Data
Let me walk you through a few practical examples of how to use cryptography in .NET applications. I'll show you private and public key algorithms as well as hashing. At this point you may wonder when to use symmetric, private key algorithms instead of asymmetric, public key algorithms. I know of one golden rule that may help you to decide. Symmetric encryption is ideal to encrypt large amounts of data, and subsequently is designed to work on streams. Microsoft provides the CryptoStream class (more on this shortly), which works on top of an existing Stream class and automatically encrypts its contents. The CryptoStream class is the recommended and most effective way to work with symmetric cryptography from within managed applications.
|.NET Framework classes define a wrapper object to access the cryptographic service provider for particular algorithm chosen.|
In contrast, asymmetric encryption is recommended for small amounts of data and is typically used to encrypt keys. Let's begin with public key encryption and consider the RSA service provider.
First create an instance of the service provider.
rsa = new RSACryptoServiceProvider();
Next, configure it by importing a parameter object. The parameter class is named RSAParameters
and you load it using the method ImportParameters
info = new RSAParameters();
info.Modulus = PublicKey;
info.Exponent = Exponent;
The necessary parametersmodulus and exponenthave to do with the internal cryptographic system used by the algorithm. The RSA algorithm works by taking two large primes (say P and Q) and computes their product. This value is known as the modulus
. Next, it takes a number, say E, less than the modulus and relatively prime to (P-1)*(Q-1). Another number, say D, is found such that its product by E is divisible by (P-1)*(Q-1).
The values E and D are called the public and the private exponents
. The modulus and the public exponent form the public key for the RSA algorithm. You only need to pass these two parameters to encrypt some data. Similarly, you form the private key using the modulus and the private exponent. At this point, to encrypt and decrypt you no longer need the two large prime numbers from which everything originated. The letters used are not coincidental as they appear in the original paper of the authors and also name the various members of the RSAParameters
class. The RSA algorithm was invented by Ronald L. Rivest, Adi Shamir, and Leonard Adleman in 1977.
Once you configure the parameters you only need to call the Encrypt
methods. To encrypt you pass the input data as an array of bytes and get an array of scrambled bytes. The Decrypt
method takes an array of scrambled bytes and returns outputthe decrypted valueas an array of bytes.