Use rc2cryptoserviceprovider for encryption. In framework1.1, IV can use less than 8 bits. However, in Framework 2.0, IV must contain at least 8 bits. Otherwise, an exception is thrown! If the framework class library is reflected, an exception is added. If the length is less than 8 bits, an exception is thrown. ms has always been backward compatible, but isn't the encrypted data with less than 7 bits in framework1.1 used in Framework 2.0?
The followingCodeIt can be passed in Framework 1.1, but not in Framework 2.0. Pay attention to the IV length.
Using System;
Using System. IO;
Using System. text;
Using System. Security. cryptography;
Namespace Rc2cryptoserviceprovider_examples
{
Class Mymainclass1
{
Public Static Void Main ()
{
// Create a new instance of the rc2cryptoserviceprovider class
// And automatically generate a key and IV.
Rc2cryptoserviceprovider rc2csp = New Rc2cryptoserviceprovider ();
Console. writeline ( " Valid key size is {0} bits. " , Rc2csp. effectivekeysize );
String Striv = " 1234567 " ;
// Get the key and IV.
Byte [] Key = Rc2csp. Key;
Byte [] IV; // = Rc2csp. IV;
IV = Asciiencoding. ASCII. getbytes (striv );
// Get an encryptor.
Icryptotransform encryptor = Rc2csp. createencryptor (Key, IV );
// Encrypt the data as an array of encrypted bytes in memory.
Memorystream msencrypt = New Memorystream ();
Cryptostream csencrypt = New Cryptostream (msencrypt, encryptor, cryptostreammode. Write );
// Convert the data to a byte array.
String Original = " Here is some data to encrypt. " ;
Byte [] Toencrypt = Encoding. ASCII. getbytes (original );
// Write all data to the crypto stream and flush it.
Csencrypt. Write (toencrypt, 0 , Toencrypt. Length );
Csencrypt. flushfinalblock ();
// Get the encrypted array of bytes.
Byte [] Encrypted = Msencrypt. toarray ();
/**/ /**/
/**/ //////////////////////////////////////// ///////////////
// This is where the data cocould be transmitted or saved.
/**/ /**/
/**/ //////////////////////////////////////// ///////////////
// Get a decryptor that uses the same key and IV as the encryptor.
Icryptotransform decryptor = Rc2csp. createdecryptor (Key, IV );
// Now decrypt the previusly encrypted message using the decryptor
// Obtained in the above step.
Memorystream msdecrypt = New Memorystream (encrypted );
Cryptostream csdecrypt = New Cryptostream (msdecrypt, decryptor, cryptostreammode. Read );
Byte [] Fromencrypt = New Byte [Toencrypt. Length];
// Read the data out of the crypto stream.
Csdecrypt. Read (fromencrypt, 0 , Toencrypt. Length );
// Convert the byte array back into a string.
String roundtrip = Encoding. ASCII. getstring (fromencrypt );
// Display the original data and the decrypted data.
Console. writeline ( " Original: {0} " , Original );
Console. writeline ( " Round trip: {0} " , Roundtrip );
Console. Readline ();
}
}
}