スキップしてメイン コンテンツへ

 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日 16: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日 16: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