Source program. ^
Using System;
Using System. Text;
Using System. Runtime. InteropServices;
Using System. Security. Cryptography;
Using System. IO;
Namespace Utility
{
/** // <Summary>
/// The DSAPI wrapper
/// Security encryption algorithm for future extension
/// To be released as part of the Microsoft Configuration Building Block
/// </Summary>
Public class DataProtector
{
// Private parameter ricalgorithm mCSP;
/** // <Summary>
/// Create a base class of the symmetric encryption algorithm
/// </Summary>
Private System. Security. Cryptography. SymmetricAlgorithm mCSP;
/** // <Summary>
/// KeyOne
/// </Summary>
Private string _ KeyGen = "qA3cLz8Y9Xw = ";
/** // <Summary>
/// KeyTwo
/// </Summary>
Private string _ IVGen = "uHnaoO/MEDw = ";
/** // <Summary>
/// Generate a random initialization Vector used for this algorithm, and return a string
/// </Summary>
/// <Returns> </returns>
Public string GenerateKeyGen ()
{
MCSP = SetEnc ();
MCSP. GenerateKey ();
Return Convert. ToBase64String (mCSP. Key );
}
/** // <Summary>
/// Generate a random Key for this algorithm and return a string
/// </Summary>
/// <Returns> </returns>
Public string GenerateIVGen ()
{
MCSP. GenerateIV ();
Return Convert. ToBase64String (mCSP. IV );
}
/** // <Summary>
/// Select the encryption algorithm. By default, DESCryptoServiceProvider is selected for encryption.
/// </Summary>
/// <Returns> </returns>
Private parameter ricalgorithm SetEnc ()
{
Return new DESCryptoServiceProvider ();
// Return new DESCryptoServiceProvider ();
// Return new TripleDESCryptoServiceProvider ();
}
/** // <Summary>
/// Encryption (using the _ KeyGen, _ IVGen of this class for symmetric keys)
/// </Summary>
/// <Param name = "Value"> </param>
/// <Returns> </returns>
Public string EncryptString (string Value)
{
ICryptoTransform ct;
MemoryStream MS;
CryptoStream cs;
Byte [] byt;
MCSP. Key = Convert. FromBase64String (this. _ KeyGen );
MCSP. IV = Convert. FromBase64String (this. _ IVGen );
Ct = mCSP. CreateEncryptor (mCSP. Key, mCSP. IV );
// Ct = mCSP. CreateEncryptor ();
Byt = Encoding. UTF8.GetBytes (Value );
MS = new MemoryStream ();
Cs = new CryptoStream (MS, ct, CryptoStreamMode. Write );
Cs. Write (byt, 0, byt. Length );
Cs. FlushFinalBlock ();
Cs. Close ();
Return Convert. ToBase64String (ms. ToArray ());
}
/** // <Summary>
/// Decrypt
/// </Summary>
/// <Param name = "Value"> </param>
/// <Returns> </returns>
Public string DecryptString (string Value)
{
ICryptoTransform ct;
MemoryStream MS;
CryptoStream cs;
Byte [] byt;
MCSP. Key = Convert. FromBase64String (this. _ KeyGen );
MCSP. IV = Convert. FromBase64String (this. _ IVGen );
Ct = mCSP. CreateDecryptor (mCSP. Key, mCSP. IV );
Byt = Convert. FromBase64String (Value );
MS = new MemoryStream ();
Cs = new CryptoStream (MS, ct, CryptoStreamMode. Write );
Cs. Write (byt, 0, byt. Length );
Cs. FlushFinalBlock ();
Cs. Close ();
Return Encoding. UTF8.GetString (ms. ToArray ());
}
}
}