주 콘텐츠로 건너뛰기

 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.
    2009년 10월 11일 일요일 오전 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 2009년 10월 12일 월요일 오전 9:58
    • 답변으로 표시 취소됨 Nitin Mogha 2009년 10월 12일 월요일 오전 9:58
    • 답변으로 제안됨 Tamer Oz 2009년 10월 12일 월요일 오후 4:36
    • 답변으로 표시됨 Aland LiModerator 2009년 10월 13일 화요일 오전 5:51
    2009년 10월 11일 일요일 오전 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 2009년 10월 12일 월요일 오전 9:58
    • 답변으로 표시 취소됨 Nitin Mogha 2009년 10월 12일 월요일 오전 9:58
    • 답변으로 제안됨 Tamer Oz 2009년 10월 12일 월요일 오후 4:36
    • 답변으로 표시됨 Aland LiModerator 2009년 10월 13일 화요일 오전 5:51
    2009년 10월 11일 일요일 오전 9:14
  • Thank you
    2009년 10월 12일 월요일 오전 10:02
  • Could you write me a decode algorythm for md5? i cant find anywhere...
    2015년 6월 6일 토요일 오전 11:24