In use. NET Framework to perform cryptographic tasks, you need to prepare the encryption key and initialization vector (initialization vector,iv). Based on the characteristics of symmetric encryption, it is important to preserve the key and initialization vectors after the data is encrypted, because they are used for decryption. But for different data encryption, using different keys and initialization vectors, each new encryption process should theoretically use a brand-new key and initialization vector.
It is usually necessary to pass the encryption key and initialization vector to another person, which requires an asymmetric encryption algorithm to encrypt the key and initialize the vector, and then transfer over the network. This section mainly demonstrates how to use cryptographic practice classes, and more applications are introduced in part Fourth of this book.
So how do you create encryption keys and initialization vectors? There are two basic methods, one is to implement the constructor of the class using the cryptographic algorithm, the other is to generate the key and initialization vector using the GenerateIV () and GenerateKey () methods.
Creating keys and initializing vectors using constructors
Test the constructor's method first, such as listing 6-5.
Code listing 6-5 creating keys and initializing vectors using constructors
using System;
Using System.Text;
Using System.Security.Cryptography;
Namespace Encription {classprogram {staticvoid Main (string[] args) {
Aescryptoserviceprovider ACSP = new Aescryptoserviceprovider ();
Writekeyandiv (ACSP);
aesmanaged am = newaesmanaged ();
Writekeyandiv (AM);
DESCryptoServiceProvider DSP = new DESCryptoServiceProvider ();
Writekeyandiv (DSP);
TripleDESCryptoServiceProvider TDSP = new TripleDESCryptoServiceProvider ();
Writekeyandiv (TDSP);
RijndaelManaged rm = new RijndaelManaged ();
Writekeyandiv (RM);
Console.read (); } staticvoid Writekeyandiv (SymmetricAlgorithm sa) {Console.WriteLine (GetString Frombyte (SA.
Key));
Console.WriteLine ("*******"); Console.WriteLine (Getstringfrombyte (SA.IV));
Console.WriteLine ("--------------------------");
} staticstring getstringfrombyte (byte[] bytes) {string s= ""; for (int i = 0; i < bytes. Length; i++) {s + = Bytes[i].
ToString () + "";
return s; }
}
}