none
How to Encrypt and Decrypt using C# in window base programme RRS feed

  • Question

  • Dear all,

    Please help me in solving following query.

    I want to use Encryption and Decryption to add password to database and to retrive password from database.

    What is the code for this?

    Thanks and regards.

    Nitin Kumar.
    Sunday, October 11, 2009 8:51 AM

Answers

  • Hi,

    For 3Des you can use the class below.
    But instead of storing passwords with encrypting and after checking with decrypting is not a good idea.
    Using hash(one way, ex MD5) is much better idea for this purpose. You hash the password and store it to db. When user wants to log on you hash the password again and check if the hashed strings are same.

    I'll also post a method for MD5 hash at the bottom.

        public  class Crypto
        {
            SymmetricAlgorithm mCSP;
            #region "Constants"
            private object _key = "12345678";
            #endregion
            public Crypto()
            {
    
            }
        
            public bool HasKey()
            {
                return (!(_key == null  || _key.ToString()=="" ));
            }
            private string SetLengthString(string str, int length)
            {
                while (length > str.Length)
                {
                    str += str;
                }
                if (str.Length > length)
                {
                    str = str.Remove(length);
                }
                return str;
            }
            public string EncryptString(string Value)
            {
                mCSP = SetEnc();
                string iv = "PenS8UCVF7s=";
                mCSP.IV = Convert.FromBase64String(iv);
                string key = SetLengthString(_key.ToString(), 32);
                mCSP.Key = Convert.FromBase64String(key);
                ICryptoTransform ct;
                MemoryStream ms;
                CryptoStream cs;
                Byte[] byt = new byte[64];
    
                try
                {
                    ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
    
                    byt = Encoding.UTF8.GetBytes(Value);
                    
                    ms = new MemoryStream();
                    cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                    cs.Write(byt, 0, byt.Length);
                    cs.FlushFinalBlock();
    
                    cs.Close();
    
                    return Convert.ToBase64String(ms.ToArray());
                }
                catch (Exception Ex)
                {
                    throw (new Exception("An error occurred while encrypting string"));
                }
    
    
            }
    
            public string DecryptString(string Value)
            {
                mCSP = SetEnc();
                string iv = "PenS8UCVF7s=";
                mCSP.IV = Convert.FromBase64String(iv);
                string key = SetLengthString(_key.ToString(), 32);
                mCSP.Key = Convert.FromBase64String(key);
                ICryptoTransform ct;
                MemoryStream ms;
                CryptoStream cs;
                Byte[] byt = new byte[64];
                try
                {
                    ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
    
                    byt = Convert.FromBase64String(Value);
    
                    ms = new MemoryStream();
                    cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                    cs.Write(byt, 0, byt.Length);
                    cs.FlushFinalBlock();
    
                    cs.Close();
                    
                    string str= Encoding.UTF8.GetString(ms.ToArray());
                }
                catch (Exception ex)
                {
                    throw (new Exception("An error occurred while decrypting string"));
                }
    
    
            }
            private SymmetricAlgorithm SetEnc()
            {
    
            return new TripleDESCryptoServiceProvider();
            }
    
        
        }
    And this is for MD5

        public class MD5Crypto
        {
            private static byte[] ToByteArray(object value)
            {
                byte[] result = new byte[] { };
                string val = value as string;
                if (val != null)
                    result = new System.Text.UnicodeEncoding().GetBytes(val);
                return result;
            }
            public static string Tomd5(string value)
            {
                byte[] hash = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(ToByteArray(value));
                string result = System.BitConverter.ToString(hash);
                result = result.Replace("-", "");
                return result;
            }
    
    
        }


    • Marked as answer by Nitin Mogha Monday, October 12, 2009 9:58 AM
    • Unmarked as answer by Nitin Mogha Monday, October 12, 2009 9:58 AM
    • Proposed as answer by Tamer Oz Monday, October 12, 2009 4:36 PM
    • Marked as answer by Aland LiModerator Tuesday, October 13, 2009 5:51 AM
    Sunday, October 11, 2009 9:14 AM

All replies

  • Hi,

    For 3Des you can use the class below.
    But instead of storing passwords with encrypting and after checking with decrypting is not a good idea.
    Using hash(one way, ex MD5) is much better idea for this purpose. You hash the password and store it to db. When user wants to log on you hash the password again and check if the hashed strings are same.

    I'll also post a method for MD5 hash at the bottom.

        public  class Crypto
        {
            SymmetricAlgorithm mCSP;
            #region "Constants"
            private object _key = "12345678";
            #endregion
            public Crypto()
            {
    
            }
        
            public bool HasKey()
            {
                return (!(_key == null  || _key.ToString()=="" ));
            }
            private string SetLengthString(string str, int length)
            {
                while (length > str.Length)
                {
                    str += str;
                }
                if (str.Length > length)
                {
                    str = str.Remove(length);
                }
                return str;
            }
            public string EncryptString(string Value)
            {
                mCSP = SetEnc();
                string iv = "PenS8UCVF7s=";
                mCSP.IV = Convert.FromBase64String(iv);
                string key = SetLengthString(_key.ToString(), 32);
                mCSP.Key = Convert.FromBase64String(key);
                ICryptoTransform ct;
                MemoryStream ms;
                CryptoStream cs;
                Byte[] byt = new byte[64];
    
                try
                {
                    ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
    
                    byt = Encoding.UTF8.GetBytes(Value);
                    
                    ms = new MemoryStream();
                    cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                    cs.Write(byt, 0, byt.Length);
                    cs.FlushFinalBlock();
    
                    cs.Close();
    
                    return Convert.ToBase64String(ms.ToArray());
                }
                catch (Exception Ex)
                {
                    throw (new Exception("An error occurred while encrypting string"));
                }
    
    
            }
    
            public string DecryptString(string Value)
            {
                mCSP = SetEnc();
                string iv = "PenS8UCVF7s=";
                mCSP.IV = Convert.FromBase64String(iv);
                string key = SetLengthString(_key.ToString(), 32);
                mCSP.Key = Convert.FromBase64String(key);
                ICryptoTransform ct;
                MemoryStream ms;
                CryptoStream cs;
                Byte[] byt = new byte[64];
                try
                {
                    ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
    
                    byt = Convert.FromBase64String(Value);
    
                    ms = new MemoryStream();
                    cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                    cs.Write(byt, 0, byt.Length);
                    cs.FlushFinalBlock();
    
                    cs.Close();
                    
                    string str= Encoding.UTF8.GetString(ms.ToArray());
                }
                catch (Exception ex)
                {
                    throw (new Exception("An error occurred while decrypting string"));
                }
    
    
            }
            private SymmetricAlgorithm SetEnc()
            {
    
            return new TripleDESCryptoServiceProvider();
            }
    
        
        }
    And this is for MD5

        public class MD5Crypto
        {
            private static byte[] ToByteArray(object value)
            {
                byte[] result = new byte[] { };
                string val = value as string;
                if (val != null)
                    result = new System.Text.UnicodeEncoding().GetBytes(val);
                return result;
            }
            public static string Tomd5(string value)
            {
                byte[] hash = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(ToByteArray(value));
                string result = System.BitConverter.ToString(hash);
                result = result.Replace("-", "");
                return result;
            }
    
    
        }


    • Marked as answer by Nitin Mogha Monday, October 12, 2009 9:58 AM
    • Unmarked as answer by Nitin Mogha Monday, October 12, 2009 9:58 AM
    • Proposed as answer by Tamer Oz Monday, October 12, 2009 4:36 PM
    • Marked as answer by Aland LiModerator Tuesday, October 13, 2009 5:51 AM
    Sunday, October 11, 2009 9:14 AM
  • Thank you
    Monday, October 12, 2009 10:02 AM
  • Could you write me a decode algorythm for md5? i cant find anywhere...
    Saturday, June 6, 2015 11:24 AM