Перейти к основному контенту
Центр разработки для Windows

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

  • Вопрос

  • 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.
    11 октября 2009 г. 8:51

Ответы

  • 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;
            }
    
    
        }


    • Помечено в качестве ответа Nitin Mogha 12 октября 2009 г. 9:58
    • Снята пометка об ответе Nitin Mogha 12 октября 2009 г. 9:58
    • Предложено в качестве ответа Tamer Oz 12 октября 2009 г. 16:36
    • Помечено в качестве ответа Aland LiModerator 13 октября 2009 г. 5:51
    11 октября 2009 г. 9:14

Все ответы

  • 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;
            }
    
    
        }


    • Помечено в качестве ответа Nitin Mogha 12 октября 2009 г. 9:58
    • Снята пометка об ответе Nitin Mogha 12 октября 2009 г. 9:58
    • Предложено в качестве ответа Tamer Oz 12 октября 2009 г. 16:36
    • Помечено в качестве ответа Aland LiModerator 13 октября 2009 г. 5:51
    11 октября 2009 г. 9:14
  • Thank you
    12 октября 2009 г. 10:02
  • Could you write me a decode algorythm for md5? i cant find anywhere...
    6 июня 2015 г. 11:24