password save into sql server as encrypted

Last post 07-05-2009 12:52 PM by RickNZ. 9 replies.

Sort Posts:

  • password save into sql server as encrypted

    07-04-2009, 5:38 PM
    • Member
      16 point Member
    • tejp
    • Member since 11-26-2006, 9:18 PM
    • Posts 138

    Hi

    I am having a login option on my website. So user will enter their username and password to log in.

    But i when first creating the password it will be displayed to the user but i want to save it into the sql server database as hashes or any other encrypted form

    how can i achieve this?

    any help would be great


    tj

  • Re: password save into sql server as encrypted

    07-04-2009, 6:51 PM
    Answer
    • Contributor
      4,934 point Contributor
    • Segundo
    • Member since 09-07-2006, 2:44 PM
    • Lima, Perú
    • Posts 693

     Hi mate,

    here is some useful link:

    http://www.codeproject.com/KB/web-security/encrypt.aspx

    http://www.4guysfromrolla.com/articles/112002-1.aspx

    Any doubt, post your comment.

     

  • Re: password save into sql server as encrypted

    07-04-2009, 11:16 PM
    • All-Star
      63,161 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 1:34 PM
    • England
    • Posts 12,331
    • TrustedFriends-MVPs

    >I want to save it into the sql server database as hashes or any other encrypted form

    Passwords should be hashed, preferably incorporating the Id of the user record into the plaintext before hashing. For some code for hashing please look at the common data solution at http://www.codeplex.com/CommonData

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: password save into sql server as encrypted

    07-04-2009, 11:42 PM
    Answer
    • Contributor
      5,228 point Contributor
    • RickNZ
    • Member since 01-01-2009, 3:43 AM
    • Nelson, New Zealand
    • Posts 873

    You might want to look into using the built-in Membership system -- it will handle all of this stuff for you.

    However, if you would prefer to do it yourself, here's how to do hashing:

    using System.Security.Cryptography;
    
    public static byte[] HashStringSHA1(string input)
    {
        byte[] inbytes = input.GetBytes();
        SHA1 sha = new SHA1CryptoServiceProvider();
        byte[] hash = sha.ComputeHash(inbytes);
        return hash;
    }
    
    byte[] hashedPassword = HashStringSHA1(password + hashKey);
    
    

    Then store the result in the DB as a varbinary.

    For the hash key, pick something that's different from one user to another, and that won't change.  Their username is one possibility.

  • Re: password save into sql server as encrypted

    07-05-2009, 12:51 AM
    • All-Star
      63,161 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 1:34 PM
    • England
    • Posts 12,331
    • TrustedFriends-MVPs

    Here is the hash function from CommonData

        /// <summary>
        /// Salt String
        /// </summary>
        private const string Salt = "Dingbat"; // you should amend this to a random string before use.

        #region " HashPassword and HashStringToString "
        /// <summary>
        /// Hash password
        /// </summary>
        /// <param name="input">Input hash to encode</param>
        /// <returns>Byte array of hashed password</returns>
        /// <remarks>This replaces the now dubious MD5 version</remarks>
        public static byte[] HashPassword(string input)
        {
          var provider = new SHA256Managed();
          var encoder = new UTF8Encoding();
          var hashedBytes = provider.ComputeHash(encoder.GetBytes(Salt + input));
          return hashedBytes;
        }

        /// <summary>
        /// Hash string to hex string
        /// </summary>
        /// <param name="input">Input hash to decode</param>
        /// <returns>Hashed string</returns>
        public static string HashStringToHexString(string input)
        {
          return HashToHexString(HashPassword(input));
        }

        /// <summary>
        /// Hash string
        /// </summary>
        /// <param name="input">Input hash to decode</param>
        /// <returns>Hashed string</returns>
        public static string HashStringToString(string input)
        {
          return HashToString(HashPassword(input));
        }

        /// <summary>
        /// Hash string
        /// </summary>
        /// <param name="input">Input hash to decode</param>
        /// <param name="number">number e.g. id of user </param>
        /// <returns>Hashed string</returns>
        public static string HashStringToHexString(string input, int number)
        {
          return HashToHexString(HashPassword(input + number.ToString(CultureInfo.InvariantCulture)));
        }

        /// <summary>
        /// Hash string to hex string
        /// </summary>
        /// <param name="input">Input hash to decode</param>
        /// <param name="number">number e.g. id of user </param>
        /// <returns>Hashed string</returns>
        public static string HashStringToString(string input, int number)
        {
          return HashToString(HashPassword(input + number.ToString(CultureInfo.InvariantCulture)));
        }
        #endregion
        #region " HashToHexString "
        /// <summary>
        /// Convert Byte Array to hexadecimal string
        /// </summary>
        /// <param name="hashedValue">hash string to decode</param>
        /// <returns>base 16 version of hash  array</returns>
        public static string HashToHexString(byte[] hashedValue)
        {
          var work = new StringBuilder(2 * hashedValue.Length);
          for (var i = 0; i < hashedValue.Length; i++)
          {
            var item = Convert.ToString(hashedValue[i], 16);
            if (item.Length < 2)
            {
              item = "0" + item;
            }
            if (item.Length < 2)
            {
              item = "0" + item;
            }
            work.Append(item);
          }
          return work.ToString();
        }
        #endregion
        #region " HashToString "
        /// <summary>
        /// Convert Byte Array to string
        /// </summary>
        /// <param name="hashedValue">hash string to decode</param>
        /// <returns>base 10 version of hash  array</returns>
        public static string HashToString(byte[] hashedValue)
        {
          var work = new StringBuilder(3 * hashedValue.Length);
          for (var i = 0; i < hashedValue.Length; i++)
          {
            work.Append(hashedValue[i].ToString("000", CultureInfo.InvariantCulture));
          }
          return work.ToString();
        }
        #endregion

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: password save into sql server as encrypted

    07-05-2009, 1:45 AM
    Answer
    • Contributor
      2,770 point Contributor
    • anup1252000
    • Member since 11-12-2008, 8:26 AM
    • india
    • Posts 554

    writes these lines of code in ur code behind

    private string bytetoencode(string data)
        {
            try
            {
                byte[] encyrpt = new byte[data.Length];
                encyrpt = System.Text.Encoding.UTF8.GetBytes(data);
                string encodedata = Convert.ToBase64String(encyrpt);
                Response.Write(encodedata);
                return encodedata;

            }
            catch (Exception ex)
            {

                throw new Exception("error in exception" + ex.Message);
            }
           
        }

        private string decode(string data)
        {
            UTF8Encoding encoder = new UTF8Encoding();
            Decoder decode = encoder.GetDecoder();
            byte[] bytes = Convert.FromBase64String(data);
            int count = decode.GetCharCount(bytes, 0, bytes.Length);
            char[] decodechar = new char[count];
            decode.GetChars(bytes,0,bytes.Length,decodechar,0);
            string result = new string(decodechar);
            Response.Write(result);
            return result;
           
        }


    then u the insert command i dont ur exact requirement.. so i m sending this much of code...

    Remember to click “Mark as Answer” on the post, if it helps you. Because It helps others to find the solution.

    Anup Hosur
    HP
    http://anup-anuphosur.blogspot.com/


  • Re: password save into sql server as encrypted

    07-05-2009, 1:58 AM
    Answer
    • All-Star
      63,161 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 1:34 PM
    • England
    • Posts 12,331
    • TrustedFriends-MVPs

    Here is a unit test function (that passes!) that tests the hash function:

        /// <summary>
        /// Test HashStringToString
        /// </summary>
        [Test]
        public void TestHashStringToString()
        {
          Console.WriteLine("000000000111111111122222222223333333333444444444");
          Console.WriteLine("123456789012345678901234567890123456789012345678");
          string[] hash =
          {
            CommonData.HashStringToString("A"),
            CommonData.HashStringToString("B"),
            CommonData.HashStringToString("C"),
            CommonData.HashStringToString("AB"),
            CommonData.HashStringToString("ABC"),
            CommonData.HashStringToString("ABCD"),
            CommonData.HashStringToString("ABCDE"),
            CommonData.HashStringToString("ABCDEF"),
            CommonData.HashStringToString("FAAAAA"),
            CommonData.HashStringToString("AFAAAA"),
            CommonData.HashStringToString("AAFAAA"),
            CommonData.HashStringToString("AAAFAA"),
            CommonData.HashStringToString("AAAAFA"),
            CommonData.HashStringToString("AAAAAF"),
            CommonData.HashStringToString("BACDEF"),
            CommonData.HashStringToString("AAAAAA"),
            CommonData.HashStringToString("AAAAAB"),
            CommonData.HashStringToString("AAAABA"),
            CommonData.HashStringToString("AAABAA"),
            CommonData.HashStringToString("AABAAA"),
            CommonData.HashStringToString("ABAAAA"),
            CommonData.HashStringToString("BAAAAA"),
            CommonData.HashStringToString("FYYYYY"),
            CommonData.HashStringToString("YFYYYY"),
            CommonData.HashStringToString("YYFYYY"),
            CommonData.HashStringToString("YYYFYY"),
            CommonData.HashStringToString("YYYYFY"),
            CommonData.HashStringToString("YYYYYF"),
            CommonData.HashStringToString("BYCDEF"),
            CommonData.HashStringToString("YYYYYY"),
            CommonData.HashStringToString("YYYYYB"),
            CommonData.HashStringToString("YYYYBY"),
            CommonData.HashStringToString("YYYBYY"),
            CommonData.HashStringToString("YYBYYY"),
            CommonData.HashStringToString("YBYYYY"),
            CommonData.HashStringToString("BYYYYY"),
            CommonData.HashStringToString("FXXXXX"),
            CommonData.HashStringToString("XFXXXX"),
            CommonData.HashStringToString("XXFXXX"),
            CommonData.HashStringToString("XXXFXX"),
            CommonData.HashStringToString("XXXXFX"),
            CommonData.HashStringToString("XXXXXF"),
            CommonData.HashStringToString("BXCDEF"),
            CommonData.HashStringToString("XXXXXX"),
            CommonData.HashStringToString("XXXXXB"),
            CommonData.HashStringToString("XXXXBX"),
            CommonData.HashStringToString("XXXBXX"),
            CommonData.HashStringToString("XXBXXX"),
            CommonData.HashStringToString("XBXXXX"),
            CommonData.HashStringToString("BXXXXX"),
            CommonData.HashStringToString("FZZZZZ"),
            CommonData.HashStringToString("ZFZZZZ"),
            CommonData.HashStringToString("ZZFZZZ"),
            CommonData.HashStringToString("ZZZFZZ"),
            CommonData.HashStringToString("ZZZZFZ"),
            CommonData.HashStringToString("ZZZZZF"),
            CommonData.HashStringToString("BZCDEF"),
            CommonData.HashStringToString("ZZZZZZ"),
            CommonData.HashStringToString("ZZZZZB"),
            CommonData.HashStringToString("ZZZZBZ"),
            CommonData.HashStringToString("ZZZBZZ"),
            CommonData.HashStringToString("ZZBZZZ"),
            CommonData.HashStringToString("ZBZZZZ"),
            CommonData.HashStringToString("BZZZZZ")
          };
          for (var i1 = 0; i1 < hash.Length; i1++)
          {
            Console.WriteLine(i1.ToString("000", CultureInfo.InvariantCulture) + ":" + hash[i1]
              + ": Len=" + hash[i1].Length.ToString(CultureInfo.InvariantCulture));
            for (var i2 = i1 + 1; i2 < hash.Length; i2++)
            {
              Assert.AreNotEqual(hash[i1], hash[i2]);
            }
          }
        }

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: password save into sql server as encrypted

    07-05-2009, 8:14 AM
    • Member
      16 point Member
    • tejp
    • Member since 11-26-2006, 9:18 PM
    • Posts 138

    Thanks for the reply guys.

    I will give them a go.

    But i wanted to know what data type should the password field be in the server? bit? binary?


    cheers

  • Re: password save into sql server as encrypted

    07-05-2009, 11:32 AM
    • All-Star
      63,161 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 1:34 PM
    • England
    • Posts 12,331
    • TrustedFriends-MVPs

    >But i wanted to know what data type should the password field be in the server? bit? binary?

    If you use the CommonData HashToHexString you should make the password column char(64) as the as the output of HashToHexString is a fixed 64-bytes.

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: password save into sql server as encrypted

    07-05-2009, 12:52 PM
    • Contributor
      5,228 point Contributor
    • RickNZ
    • Member since 01-01-2009, 3:43 AM
    • Nelson, New Zealand
    • Posts 873

    tejp:

    But i wanted to know what data type should the password field be in the server? bit? binary

    To hold an array of bytes (which is the output of the hashing function), the SQL data type should be varbinary.  The length depends on which hashing algorithm you use -- or you can just set it to varbinary(max) if you don't know.


Page 1 of 1 (10 items)