asp.net 如何将密码以加密格式存储在从Web应用程序输入的数据库中?

4ngedf3f  于 2023-06-25  发布在  .NET
关注(0)|答案(8)|浏览(148)

在我的应用程序中有一个密码字段。当用户输入密码时,它应该加密密码并存储到数据库中。当用户登录到该应用程序,然后密码应该从数据库中获取,并且应该进行解密。
这可能吗??

fcwjkofz

fcwjkofz1#

你可以看看this链接,它可以让你开始正确的方向。
然而,尽管如此,通常的做法是存储密码本身的散列值,而不是密码的加密版本。哈希将允许您检查用户是否输入了正确的密码(通过比较您在数据库中的哈希值与用户输入的任何哈希值),而不需要知道实际密码是什么。
这样做的好处是,它通常更简单,更安全,因为您不需要加密/解密任何值。使用散列的缺点是,你永远不能 * 发送 * 用户他们的密码(如果你打算提供某种“忘记密码”功能),而是你必须将其重置为一个新的随机密码。

wfveoks0

wfveoks02#

如果您不希望使用ASP.NET成员资格和角色提供程序,这可能对您有用:

/// <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);
    }

使用上述两种方法,您可以在密码字符串保存到数据库时对其进行加密,并在检索时对其进行解密。

ymdaylpp

ymdaylpp3#

您可以在SQL SERVER中创建SQLCLR UDF,有两个主要的方法我用来保存密码的加密格式。
Pwdencryp()t加密密码,返回加密字符串。设置密码时使用此选项,加密的密码存储在master..syslogins表中。
http://msdn.microsoft.com/en-us/library/dd822791(v=sql.105).aspx
Pwdcompare()接受明文密码和加密密码,并通过加密明文密码并比较两者来检查它们是否匹配。键入登录SQL Server的密码时,将调用此例程。
http://msdn.microsoft.com/en-us/library/dd822792.aspx

xxe27gdn

xxe27gdn4#

ASP.NET SQL Server成员资格提供程序在配置passwordFormat="Hashed"ASP.NET password hashing and password salt时为您提供此功能
但如果你想自己卷,那么你会想研究盐密码。例如Hash and salt passwords in C#

zfycwa2u

zfycwa2u5#

简单的方法如下:

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

w8rqjzmb6#

获取哈希密码的最简单方法如下。FormsAuthentication.HashPasswordForStoringInConfigFile("value of string", FormsAuthPasswordFormat.MD5.ToString());

s5a0g9ez

s5a0g9ez7#

当然,这里有一个类,其中包含了在C# Windows窗体应用程序中加密和解密密码所必需的方法。

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());
            }
        }
    }
}

您可以使用EncryptPassword方法对用户密码进行加密,然后将其存储到数据库中,并使用DecryptPassword方法对用户密码进行解密,同时从数据库中检索以进行用户身份验证。请注意,您需要为您的实体设置一个特定的salt值,以增强密码的安全性。在上面的代码中,用salt值替换Your_Entity_Specific_Salt_Value

xytpbqjk

xytpbqjk8#

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();
        }
    }

相关问题