8

In my application there is a password field. When user enters password it should encrypt that password and store into database. When user login into that application then password should fetch from database and decryption should take place.

Is it possible??

Syed Yunus
  • 198
  • 3
  • 4
  • 14
  • 1
    Before rolling your own code you might want to looking into ASP.NET membership and role providers, http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx this is built into the framework and therefore page controls and other features of the framework integrate nicely with this – Chris Moutray May 22 '12 at 05:56
  • 1
    Your question doesn't specify if you are trying to make a password login system, or just trying to store an encrypted string for other use. If you are looking for ways to encrypt a string so it can be decrypted later, then I suggest not mentioning the word "password" at all in your question, because it will lead to a lot of misunderstandings. – Deantwo Jan 29 '19 at 14:34

8 Answers8

22

You could take a look at this link which could get you started in the right direction.

That being said however, it is the usual practice to store the hash value of the password itself rather than an encrypted version of the password. The hashing will allow you to check if the user has entered the correct password (by comparing the hash value you have in your database with the hash value of whatever the user entered) without the need of knowing what is the actual password.

The advantage of this is that it is usually simpler and more secure since you do not need to encrypt/decrypt any values. The drawback of using hashing is that you can never send the users their passwords (if you are planning to provide some sort of 'forgot my password' functionality) but rather you will have to reset it to a new, random one.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • 1
    One cannot log in to, for example, an email server using the hash of the password. Hence there are legitimate needs for two way encryption. – Micah Epps Feb 06 '18 at 14:34
  • @Micah Epps, then you are talking about storing a password for use elsewhere. It is not totally clear if that is what the original question is asking for or not. This answer correctly describe a method for password authentication, not encrypted string storing. – Deantwo Jan 29 '19 at 14:32
3

If you do not wish to use the ASP.NET Membership and Role providers, this might be useful to you :

    /// <summary>
    /// Decrypts the specified encryption key.
    /// </summary>
    /// <param name="encryptionKey">The encryption key.</param>
    /// <param name="cipherString">The cipher string.</param>
    /// <param name="useHashing">if set to <c>true</c> [use hashing].</param>
    /// <returns>
    ///  The decrypted string based on the key
    /// </returns>
    public static string Decrypt(string encryptionKey, string cipherString, bool useHashing)
    {
        byte[] keyArray;
        //get the byte code of the string

        byte[] toEncryptArray = Convert.FromBase64String(cipherString);

        System.Configuration.AppSettingsReader settingsReader =
                                            new AppSettingsReader();

        if (useHashing)
        {
            //if hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
            //release any resource held by the MD5CryptoServiceProvider

            hashmd5.Clear();
        }
        else
        {
            //if hashing was not implemented get the byte code of the key
            keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);
        }

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)

        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(
                             toEncryptArray, 0, toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);
    }

    /// <summary>
    /// Encrypts the specified to encrypt.
    /// </summary>
    /// <param name="toEncrypt">To encrypt.</param>
    /// <param name="useHashing">if set to <c>true</c> [use hashing].</param>
    /// <returns>
    /// The encrypted string to be stored in the Database
    /// </returns>
    public static string Encrypt(string encryptionKey, string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader =
                                            new AppSettingsReader();

        //If hashing use get hashcode regards to your key
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
            //Always release the resources and flush data
            // of the Cryptographic service provide. Best Practice

            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)
        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)

        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        //transform the specified region of bytes array to resultArray
        byte[] resultArray =
          cTransform.TransformFinalBlock(toEncryptArray, 0,
          toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //Return the encrypted data into unreadable string format
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

Using the two above methods you could encrypt the password string as it is being saved to the database and decrypt it on retrieval.

Sabry
  • 135
  • 2
  • 9
2

You can Create SQLCLR UDF in SQL SERVER , There are Two main Method I used to Save Password in Encrpted Format .

Pwdencryp()t encrypts a password, returning the encrypted string. This is used when you set a password, and the encrypted password is stored in the master..syslogins table.

http://msdn.microsoft.com/en-us/library/dd822791(v=sql.105).aspx

Pwdcompare() accepts a clear password and an encrypted one, and checks whether they match by encrypting the clear password and comparing the two. When you type your password to log into SQL Server, this routine is called.

http://msdn.microsoft.com/en-us/library/dd822792.aspx

kuldeep verma
  • 326
  • 2
  • 4
  • 10
  • The name `Pwdencrypt()` looks bit misleading. It creates hash of the password in place of encrypting it. Hashing and encryption aren't same. – RBT Feb 10 '22 at 10:08
1

ASP.NET SQL Server membership provider gives you this feature when you configure the passwordFormat="Hashed" ASP.NET password hashing and password salt

But it you're looking to roll your own then you'll want to research into Salted Password. For example Hash and salt passwords in C#

Community
  • 1
  • 1
Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
1

The simple way to do this is as follows:

string hashedpassword= FormsAuthentication.HashPasswordForStoringInConfigFile("your password", "SHA1");
0

The simplest way to get hash password is as follow. FormsAuthentication.HashPasswordForStoringInConfigFile("value of string", FormsAuthPasswordFormat.MD5.ToString());

JayOnDotNet
  • 398
  • 1
  • 5
  • 17
0

Sure, here's a class with necessary methods for encrypting and decrypting password in a C# Windows Form application.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public static class PasswordEncryptDecryptHelper
{
    private static readonly byte[] salt = Encoding.ASCII.GetBytes("Your_Entity_Specific_Salt_Value");

    public static string EncryptPassword(string password)
    {
        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        using (var aes = Aes.Create())
        {
            var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, salt, 10000);
            aes.Key = pbkdf2.GetBytes(32);
            aes.IV = pbkdf2.GetBytes(16);

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(passwordBytes, 0, passwordBytes.Length);
                    cryptoStream.Close();
                }
                return Convert.ToBase64String(memoryStream.ToArray());
            }
        }
    }

    public static string DecryptPassword(string encryptedPassword)
    {
        byte[] encryptedPasswordBytes = Convert.FromBase64String(encryptedPassword);
        using (var aes = Aes.Create())
        {
            var pbkdf2 = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes("Your_Password"), salt, 10000);
            aes.Key = pbkdf2.GetBytes(32);
            aes.IV = pbkdf2.GetBytes(16);

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(encryptedPasswordBytes, 0, encryptedPasswordBytes.Length);
                    cryptoStream.Close();
                }
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }
    }
}

You can use EncryptPassword method to encrypt the user password before storing it into database and use DecryptPassword method to decrypt it while retrieving from database for user authentication. Note that you need to set a specific salt value for your entity to enhance the security of your passwords. In the above code, replace Your_Entity_Specific_Salt_Value with your salt value.

John G
  • 319
  • 4
  • 8
-1
 string hashedPassword = Security.HashSHA1(txtPassword.Value.Trim());
  public class Security
    {
        public static string HashSHA1(string value)
        {
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var inputBytes = Encoding.ASCII.GetBytes(value);
            var hash = sha1.ComputeHash(inputBytes);

            var sb = new StringBuilder();
            for (var i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }
    }
Code
  • 679
  • 5
  • 9
  • SHA-1 should **absolutely not** be used for hashing passwords; it is nowhere near strong enough; this is actively harmful. SHA-1 is now officially broken. – Marc Gravell Nov 20 '20 at 10:56