.NET 雜湊碼計算API使用範例

雜湊碼的應用範圍很廣,舉凡密碼的加密,或是檔案傳輸過程的驗證,或是替一組數據(或一個檔案)產生一個短一點的認證碼,.NET Framework已經提供有現成的類別,支援最常用的MD5跟SHA等演算法,下面程式碼簡單示範叫用的程序。

 1 <%@ Page Language="C#" %>
 2 <%@ Import Namespace="System.Security.Cryptography" %>
 3 <%@ Import Namespace="System.Configuration.Provider" %>
 4 
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 6 
 7 <script runat="server">
 8     
 9     
10     protected string ComputeHash(byte[] data, string hashAlgorithmType)
11     {
12         byte[] result;
13         HashAlgorithm s = HashAlgorithm.Create(hashAlgorithmType);
14         if (s == null)
15             throw new ProviderException("Could not create a hash algorithm");
16         result = s.ComputeHash(data);
17         return Convert.ToBase64String(result);
18     }
19 
20     protected void Button1_Click(object sender, EventArgs e)
21     {
22         if (FileUpload1.HasFile)
23         {
24             StringBuilder sb = new StringBuilder();
25             sb.AppendFormat("FileName = {0}<br />", FileUpload1.FileName);
26             sb.AppendFormat("FileSize = {0:#,##0} Bytes<br />", FileUpload1.FileBytes.Length);
27 
28             string[] hashAlgorithms = new string[] { "MD5""SHA1""SHA256""SHA512" };
29             for (int i = 0; i < hashAlgorithms.Length; i++)
30             {
31                 long startTick = DateTime.Now.Ticks;
32                 string smd5 = ComputeHash(FileUpload1.FileBytes, hashAlgorithms[i]);
33                 long endTick = DateTime.Now.Ticks;
34                 double times = (endTick - startTick) / 10000D;
35                 sb.AppendFormat("{0} = {1} ({2}bytes, {3:f4}ms)<br />",hashAlgorithms[i], smd5, smd5.Length, times);
36             }
37             sb.Append("<hr/>");
38 
39             laMessage.Text += sb.ToString();
40         }
41     }
42     protected void Button2_Click(object sender, EventArgs e)
43     {
44         laMessage.Text = "";
45     }
46     
47 </script>
48 
49 <html xmlns="http://www.w3.org/1999/xhtml">
50 <head runat="server">
51     <title>Compute Hash Values</title>
52 </head>
53 <body>
54     <form id="form1" runat="server">
55         <div>
56             <asp:Label ID="Label1" runat="server" Text="Select a file:"></asp:Label>
57             <asp:FileUpload ID="FileUpload1" runat="server" Width="500px" />
58             <br />
59             <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Compute" />
60             <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Clean" /><br />
61             <br />
62             <asp:Literal ID="laMessage" runat="server"></asp:Literal>
63         </div>
64     </form>
65 </body>
66 </html>
67 


posted on 2006-11-01 12:06  Jason Cheng  阅读(507)  评论(0编辑  收藏  举报