Advertisement
imjyb1008work

HashHelper

Aug 14th, 2019
1,807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. public class HashHelper
  2.     {
  3.         public static string ToMd5(string value)
  4.         {
  5.             using (var crypto = MD5.Create())
  6.             {
  7.                 string result = Hashing(value, crypto);
  8.                 return result;
  9.             }
  10.         }
  11.  
  12.         public static string ToSha1(string value)
  13.         {
  14.             using (var crypto = SHA1.Create())
  15.             {
  16.                 string result = Hashing(value, crypto);
  17.                 return result;
  18.             }
  19.         }
  20.  
  21.         public static string ToSha256(string value)
  22.         {
  23.             using (var crypto = SHA256.Create())
  24.             {
  25.                 string result = Hashing(value, crypto);
  26.                 return result;
  27.             }
  28.         }
  29.  
  30.         public static string ToSha384(string value)
  31.         {
  32.             using (var crypto = SHA384.Create())
  33.             {
  34.                 string result = Hashing(value, crypto);
  35.                 return result;
  36.             }
  37.         }
  38.  
  39.         public static string ToSha512(string value)
  40.         {
  41.             using (var crypto = SHA512.Create())
  42.             {
  43.                 string result = Hashing(value, crypto);
  44.                 return result;
  45.             }
  46.         }
  47.  
  48.         private static string Hashing(string value, HashAlgorithm crypto)
  49.         {
  50.             //將字串編碼成 UTF8 位元組陣列
  51.             var bytes = Encoding.UTF8.GetBytes(value);
  52.  
  53.             //取得雜湊值位元組陣列
  54.             var hash = crypto.ComputeHash(bytes);
  55.  
  56.             StringBuilder result = new StringBuilder();
  57.  
  58.             foreach (var item in hash)
  59.             {
  60.                 result.Append(item.ToString("X2"));
  61.             }
  62.  
  63.             return result.ToString();
  64.         }
  65.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement