C string encryption and decryption method instance


This article illustrates the C# string encryption and decryption method. Share to everybody for everybody reference. The details are as follows:

#region  Encryption to decrypt
static string encryptKey= "Oyea";
#region  Encrypted string  public static string Encrypt(string str)
/// <summary>
///  Encrypted string
/// </summary>
/// <param name="str"> The string to encrypt </param>
/// <returns> Returns the encrypted string </returns>
public static string Encrypt(string str)
{  
    DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();  // Instantiate the add / Decrypt class object  
    byte[] key = Encoding.Unicode.GetBytes(encryptKey); // Defines a byte array used to store keys   
    byte[] data = Encoding.Unicode.GetBytes(str);// Defines an array of bytes to store the string to be encrypted
    MemoryStream MStream = new MemoryStream();// Instantiate a memory flow object     
    // Instantiate an encrypted stream object using a memory flow  
    CryptoStream CStream = new CryptoStream(MStream,descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);    
    CStream.Write(data,0, data.Length);  // Writes data to an encrypted stream     
    CStream.FlushFinalBlock();             // Release encryption stream     
    return Convert.ToBase64String(MStream.ToArray());// Returns the encrypted string
}
#endregion
#region  Decrypt string    public static string Decrypt(string str)
/// <summary>
///  Decrypt string
/// </summary>
/// <param name="str"> The string to decrypt </param>
/// <returns> Returns the decrypted string </returns>
public static string Decrypt(string str)
{    
    DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();  // Instantiate the add / Decrypt class object   
    byte[] key = Encoding.Unicode.GetBytes(encryptKey); // Defines a byte array used to store keys   
    byte[] data = Convert.FromBase64String(str);// Defines an array of bytes to store the string to be decrypted
    MemoryStream MStream = new MemoryStream();// Instantiate a memory flow object     
    // Use memory flow instances to resolve dense flow objects      
    CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);  
    CStream.Write(data,0, data.Length);      // Writes data to the decryption stream    
    CStream.FlushFinalBlock();              // Release decryption stream     
    return Encoding.Unicode.GetString(MStream.ToArray());      // Returns the decrypted string
}
#endregion
#endregion

Hopefully this article has helped you with your C# programming.