Wednesday, February 5, 2014

How to encrypt and decrypt files?

using System.Security.Cryptography;       

namespace Form1
{
    public partial class Form1 : Form
    {
        static readonly string PasswordHash = "abcdef";
        static readonly string SaltKey = "S@LT&KEY";
        static readonly string VIKey = "@afag214@#%afa";

      //************* ReadProtectedInfo() *************
        private bool ReadProtectedInfo()
        {
            try
            {
                if (!System.IO.File.Exists(@openFilePath))
                {
                    return false;
                }

                char[] delimiterChars = { ' ', '\n', '\r' };

                infoString = Decrypt(System.IO.File.ReadAllText(@openFilePath));
                info = infoString.Split(delimiterChars);

                return true;

            }
            catch (Exception e)
            {
                MessageBox.Show(this, "ReadProtectedInfo() " + e.Message, "Exception");
                return false;
            }
        }
        //************* WriteProtectedInfo() *************
        private void WriteProtectedInfo()
        {
            if (!System.IO.File.Exists(@saveFilePath))
            {
                //System.IO.Directory.CreateDirectory(@".\DatFiles\");
                var myFile = System.IO.File.Create(@saveFilePath);
                myFile.Close();
            }

            string info = Encrypt(richTextBox1.Text);

            System.IO.File.WriteAllText(@saveFilePath, info, Encoding.UTF8);
        }


        // ################### ENCRYPTION ###################
        public static string Encrypt(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }
            return Convert.ToBase64String(cipherTextBytes);
        }

        public static string Decrypt(string encryptedText)
        {
            byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
            var memoryStream = new MemoryStream(cipherTextBytes);
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
        }

No comments:

Post a Comment