在.net中使用md5功能及輸出

包含 c#, asp.net, vb.net, delphi.net 等 .net framework 的開發討論區
回覆文章
頭像
tim
文章: 1380
註冊時間: 2008年 11月 26日, 00:49

在.net中使用md5功能及輸出

文章 tim »

在 php 中有好用的 md5 function, 在 asp 中有對應的 md5.asp 寫好的 function (請參閱: http://bbs.toseek.info/cgi-bin/topic.cg ... =43&show=0) 來完成計算 md5 值的功能, 在 .net 中當然有對應的方法可以實作囉, 在 msdn 上有相當多的 sample 可以參考, 請參考,

http://msdn.microsoft.com/library/defau ... stopic.asp
http://www.weste.net/2005/4-7/17122137414.html (asp.net 用)
http://www.obviex.com/samples/hash.aspx

以上的內容對於算 hash 方法都能直接使用, 但算完後的值必須能有效轉為字串才方便利用, 則必須配合下篇內容,
http://msdn.microsoft.com/library/defau ... stopic.asp
如何將 byte[] 轉為 hex string 的功能.

整理上面的文章, 寫了一個小 sample 做為計算 md5 hash value 並輸出 string 的方法,


代碼: 選擇全部

  
            public static string MD5ToString(string val) 
            {                       
                byte[] bytearray1 = Encoding.ASCII.GetBytes(val); 
                System.Security.Cryptography.MD5CryptoServiceProvider amd5 = new MD5CryptoServiceProvider(); 
                byte[] bytearray2 = amd5.ComputeHash(bytearray1); 
                return ToHexString(bytearray2); 
            } 
     
            static char[] hexDigits = { 
            '0', '1', '2', '3', '4', '5', '6', '7', 
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; 
     
     
            public static string ToHexString(byte[] bytes) 
            { 
                char[] chars = new char[bytes.Length * 2]; 
                for (int i = 0; i < bytes.Length; i++) 
                { 
                    int b = bytes[i]; 
                    chars[i * 2] = hexDigits[b >> 4]; 
                    chars[i * 2 + 1] = hexDigits[b & 0xF]; 
                } 
                return new string(chars); 
            } 
多多留言, 整理文章, 把經驗累積下來.....
回覆文章