Monday, November 7, 2016

Encrypting and Decrypting string in c# using System.Security.Cryptography

    Its pretty simple to encrypt and decrypt a string in c#.

using System.Security.Cryptography;
 
static string key = "ABC12@#a"; // you can set any key here.

public string Encrypt(string source, string key)
{
    TripleDESCryptoServiceProvider desCryptoProvider =
new TripleDESCryptoServiceProvider();
    MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider();
    byte[] byteHash;
    byte[] byteBuff;
    byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
    desCryptoProvider.Key = byteHash;
    desCryptoProvider.Mode = CipherMode.ECB; //CBC, CFB
    byteBuff = Encoding.UTF8.GetBytes(source);
    string encoded =
        Convert.ToBase64String(desCryptoProvider.CreateEncryptor().
TransformFinalBlock(byteBuff, 0, byteBuff.Length));
    return encoded;
}

public static string Decrypt(string encodedText, string key)
{
    TripleDESCryptoServiceProvider desCryptoProvider =
new TripleDESCryptoServiceProvider();
    MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider();
    byte[] byteHash;
    byte[] byteBuff;
    byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
    desCryptoProvider.Key = byteHash;
    desCryptoProvider.Mode = CipherMode.ECB; //CBC, CFB
    byteBuff = Convert.FromBase64String(encodedText);
    string plaintext = Encoding.UTF8.GetString(desCryptoProvider.
CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
    return plaintext;
}