Create a Class public class CryptClass     {         private static byte[] Encrypt(byte[] clearText, byte[] Key, byte[] IV)         {    ...

Simple Encrypt and Decrypt in C#

6:01 AM Raghunatha 1 Comments

Create a Class

public class CryptClass
    {
        private static byte[] Encrypt(byte[] clearText, byte[] Key, byte[] IV)
        {
            MemoryStream mstreem = new MemoryStream();
            Rijndael algo = Rijndael.Create();
            algo.Key = Key;
            algo.IV = IV;
            CryptoStream cs = new CryptoStream(mstreem, algo.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(clearText, 0, clearText.Length);
            cs.Close();
            byte[] encryptedData = mstreem.ToArray();
            return encryptedData;
        }
        public static string Encrypt(string clearText, string Password)
        {
            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return Convert.ToBase64String(encryptedData);
        }
        private static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
        {
            MemoryStream mstreem = new MemoryStream();
            Rijndael algo = Rijndael.Create();
            algo.Key = Key;
            algo.IV = IV;
            CryptoStream cs = new CryptoStream(mstreem, algo.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(cipherData, 0, cipherData.Length);
            cs.Close();
            byte[] decryptedData = mstreem.ToArray();
            return decryptedData;
        }
        public static string Decrypt(string cipherText, string Password)
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return System.Text.Encoding.Unicode.GetString(decryptedData);
        }
    }


Now in your encrypting Page Call above methods as in below.

string EncryptValue = CryptClass.Encrypt("Pass Encrypt Text", "PassOwnPassword");

To decrypt the Envrypted value

 string DecryptValue = CryptClass.Decrypt(EncryptValue , "PassOwnPassword");



1 comment:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.
    北美cs代写

    ReplyDelete

Powered by Blogger.