首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 中 MD5 與 SHA1 加密的多種實作方法

     編輯:關於ASP.NET

演算法簡介

  • MD5:Message-Digest Algorithm 5,128 位雜湊值,不可逆。經 MD2、MD3、MD4 演進而來。
  • SHA1:Secure Hash Algorithm,160 位雜湊值,不可逆。

雖 2004 年王小雲教授宣告破解 MD5 等演算法,但對一般軟體應用安全性仍足夠。

常見用途

密碼加密儲存:註冊時加密存入資料庫,驗證時將輸入密碼加密後比對密文。

相關類別

演算法類別
MD5System.Security.Cryptography.MD5
System.Security.Cryptography.MD5CryptoServiceProvider
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5")
SHA1System.Security.Cryptography.SHA1
System.Security.Cryptography.SHA1CryptoServiceProvider
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1")

三種 MD5 實作方法

方法一:new 運算子建立物件

public string Get_MD5_Method1(string strSource)
{
    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] bytResult = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strSource));
    string strResult = BitConverter.ToString(bytResult, 4, 8); // 16位,取第9-25字元
    strResult = strResult.Replace("-", "");
    return strResult;
}

方法二:Create 靜態方法

public string Get_MD5_Method2(string strSource)
{
    string strResult = "";
    System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] bytResult = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource));
    for (int i = 0; i < bytResult.Length; i++)
        strResult += bytResult[i].ToString("X"); // 16進制
    return strResult;
}

方法三:HashPasswordForStoringInConfigFile

public string Get_MD5_Method3(string strSource)
{
    return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSource, "MD5");
}

安全性提醒

以上皆為伺服器端加密,用戶端傳輸時密碼為明文。銀行級應用採用客戶端 ActiveX 控制項預先加密再傳送。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved