SoFunction
Updated on 2025-03-07

C# string encryption and decryption method example

#region Encryption and decryption
static string encryptKey= "Oyea";

#region public static string Encrypt(string str)

/// <summary>
/// Encrypted string
/// </summary>
/// <param name="str">String to be encrypted</param>
/// <returns>Returns encrypted string</returns>
public static string Encrypt(string str)
{  
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //Instantiate the addition/decrypt the class object
byte[] key = (encryptKey); //Define byte array to store the key
byte[] data = (str);//Define byte array to store the string to be encrypted
MemoryStream MStream = new MemoryStream();//Instantiate the memory stream object
//Instantiate the encrypted stream object using memory stream
    CryptoStream CStream = new CryptoStream(MStream,(key, key), );    
(data,0, );  //Write data into the encrypted stream
();                                                                                                                              �
return Convert.ToBase64String(());//Return the encrypted string
}
#endregion

#region Decrypt string public static string Decrypt(string str)

/// <summary>
/// Decrypt the string
/// </summary>
/// <param name="str">String to decrypt</param>
/// <returns>Returns the decrypted string</returns>
public static string Decrypt(string str)
{    
DESCryptoServiceProvider descp = new DESCryptoServiceProvider(); //Instantiate the encrypt/decrypt the class object
byte[] key = (encryptKey); //Define byte array to store the key
byte[] data = Convert.FromBase64String(str);//Define byte array to store the string to be decrypted
MemoryStream MStream = new MemoryStream();//Instantiate the memory stream object
//Use memory stream instance to decrypt stream objects
    CryptoStream CStream = new CryptoStream(MStream, (key, key), );  
(data,0, );       //Write data into the decrypted stream
();                                                              �
return (());       //Return the decrypted string
}
#endregion
#endregion