Encrypt Decrypt text in asp .net 4.5, 4.0 and lower versions

 In this article we will see how to encrypt decrypt text, password in asp .net 4.5, 4.0 and lower versions of asp .net.

 
What is encryption and decryption?
 
Encryption is the process of converting encrypted text or data into computer and human unreadable form.
E.g. The string "Hello This is Anuj" may become "tKWn+WuU8AvXad1tfciiIrjNmUVU05xV/+HE5M0uRlyfkwlfiXVH09eER0Na3v/C" after encryption.
 
Decryption is the process of converting encrypted text or data into computer and human readable form.
E.g. The string "tKWn+WuU8AvXad1tfciiIrjNmUVU05xV/+HE5M0uRlyfkwlfiXVH09eER0Na3v/C" may become "Hello This is Anuj" after decryption.
 
 
For Asp .net 4.5: In Asp .Net 4.5 we have new methods to encrypt and decrypt data i.e. MachineKey.Protect() and MachineKey.Unprotect() these method takes two arguments fist one is text to encrypt and decrypt 
in bytes format and second argument is purpose, purpose is like key we can pass any string value. We need to pass the same purpose value to Protect and unprotect value. 
var plaintextBytes = Encoding.UTF8.GetBytes("Hello This is Anuj");
var encryptedValue = Convert.ToBase64String(MachineKey.Protect(plaintextBytes, "Anuj"));
Response.Write(encryptedValue);

Response.Write("
"); var bytes = Convert.FromBase64String(encryptedValue); var output = MachineKey.Unprotect(bytes, "Anuj"); Response.Write(Encoding.UTF8.GetString(output));
 
For Asp .net 4.0
var plaintextBytes = Encoding.UTF8.GetBytes("Hello This is Anuj");
var encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);
Response.Write(encryptedValue.ToString());

Response.Write("
"); var decryptedBytes = MachineKey.Decode(encryptedValue, MachineKeyProtection.All); var decryptedValue = Encoding.UTF8.GetString(decryptedBytes); Response.Write(decryptedValue);
 
For versions lower than Asp .net 4.0:
I have used these methods to encrypt and data from years. I can't remember about the author of the code but it has worked perfectly for me. Thanks for unknown author.
Response.Write(Encrypt("Hello This is Anuj"));
Response.Write("
"); Response.Write(Decrypt("tKWn+WuU8AvXad1tfciiIrjNmUVU05xV/+HE5M0uRlyfkwlfiXVH09eER0Na3v/C"));
Methods
 
public static string Decrypt(string TextToBeDecrypted)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        string Password = "CSC";
        string DecryptedData;

        try
        {
            byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted);

            byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
            //Making of the key for decryption
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
            //Creates a symmetric Rijndael decryptor object.
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

            MemoryStream memoryStream = new MemoryStream(EncryptedData);
            //Defines the cryptographics stream for decryption.THe stream contains decrpted data
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

            byte[] PlainText = new byte[EncryptedData.Length];
            int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
            memoryStream.Close();
            cryptoStream.Close();

            //Converting to string
            DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
        }
        catch
        {
            DecryptedData = TextToBeDecrypted;
        }
        return DecryptedData;
    }

    public static string Encrypt(string TextToBeEncrypted)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();
        string Password = "CSC";
        byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(TextToBeEncrypted);
        byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
        //Creates a symmetric encryptor object. 
        ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
        MemoryStream memoryStream = new MemoryStream();
        //Defines a stream that links data streams to cryptographic transformations
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(PlainText, 0, PlainText.Length);
        //Writes the final state and clears the buffer
        cryptoStream.FlushFinalBlock();
        byte[] CipherBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        string EncryptedData = Convert.ToBase64String(CipherBytes);

        return EncryptedData;
    }
 
Best quality Asp .Net Ajax Control Toolkit tutorials.
Very useful article. Thanks for examples and description. Just a question is there a way by which I can reduce the length of the encrypted text? "tKWn+WuU8AvXad1tfciiIrjNmUVU05xV/+HE5M0uRlyfkwlfiXVH09eER0Na3v/C" I have a problem in representing such a lengthy text in my code.
15-Nov-2013 From  Venkat
Thanks Venkat... I am afraid you cannot reduce the length of the encrypted text as it is generated by predefined methods provided by microsoft.
10-Dec-2013 From  Anuj

Give your valuable comments.

Name
Email
Comment
7 + 5 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice