萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 密碼雜湊加密實作指南

前言

在 ASP.NET Web Forms 應用程式中,妥善處理使用者密碼是資安的關鍵。絕不可將明文密碼直接儲存於資料庫,而應採用單向雜湊函式(如 SHA-256 或更強的 PBKDF2、bcrypt)進行加密。本文示範如何在登入驗證流程中,將使用者輸入的密碼進行雜湊後,與資料庫中儲存的雜湊值比對。

完整程式碼範例

private void LoginButton_Click(object sender, EventArgs e)
{
    // 1. 使用參數化查詢防止 SQL Injection
    string sql = "SELECT PasswordHash FROM Administrator WHERE AdminID = @AdminID";
    
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnStr"].ConnectionString))
    using (SqlCommand cmd = new SqlCommand(sql, conn))
    {
        cmd.Parameters.AddWithValue("@AdminID", UseridBox.Text.Trim());
        conn.Open();
        
        object result = cmd.ExecuteScalar();
        if (result != null && result != DBNull.Value)
        {
            string storedHash = result.ToString();
            
            // 2. 將使用者輸入密碼進行雜湊 (此處以 SHA256 為例,實務建議用 PBKDF2)
            string inputHash = FormsAuthentication.HashPasswordForStoringInConfigFile(PasswordTextBox.Text, "SHA256");
            
            // 3. 比對雜湊值
            if (string.Equals(inputHash, storedHash, StringComparison.OrdinalIgnoreCase))
            {
                FormsAuthentication.RedirectFromLoginPage(UseridBox.Text, true);
            }
            else
            {
                Result.Text = "密碼錯誤";
            }
        }
        else
        {
            Result.Text = "使用者不存在";
        }
    }
}

關鍵點解析

1. 參數化查詢

原始碼使用 String.Format 直接拼接 SQL 字串,極易遭受 SQL Injection 攻擊。改用 SqlCommand.Parameters 可有效防範。

2. 雜湊演算法選擇

FormsAuthentication.HashPasswordForStoringInConfigFile 屬於舊版 API,僅支援 SHA1 與 MD5。現代應用建議改用 System.Security.Cryptography 命名空間下的 PBKDF2 (Rfc2898DeriveBytes)、bcrypt 或 Argon2,並加入隨機 Salt 值,大幅提升抗暴力破解能力。

3. 安全比對

使用 string.Equals(..., StringComparison.OrdinalIgnoreCase) 進行定時比對,避免時序攻擊。

進階建議:改用 ASP.NET Core Identity

若為新專案,強烈建議直接採用 ASP.NET Core Identity 內建的密碼雜湊機制(預設使用 PBKDF2 + HMAC-SHA256 + 128-bit Salt),並搭配 UserManager<TUser>.CreateAsync 與 CheckPasswordAsync 方法,可自動處理雜湊、驗證與演算法升級。

常見錯誤修正

原始碼中變數命名錯誤:宣告 hashed 卻比對 hash,已於範例中修正為 inputHash。

copyright © 萬盛學電腦網 all rights reserved