2016-09-29 46 views
1

例如,密碼是「Hello World」,我怎樣才能讓它返回到RIPEMD160哈希字符串?它應該返回一個字符串:「a830d7beb04eb7549ce990fb7dc962e499a27230」。我已經在互聯網上搜索了我的問題的答案,而不是字符串代碼是關於加密文件到RIPEMD160。C#:如何散列字符串到RIPEMD160

回答

0

好的我已經知道問題的解決方案。將字符串轉換爲一個字節,將其傳遞給RIPEMD160函數,創建一個StringBuilder並傳遞RIPEMD160函數的返回字節,將返回的StringBuilder轉換爲字符串,並再次將其轉換爲小寫。我爲它創建了一個函數。這裏是我的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Security.Cryptography; 

namespace Password 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string thePassword = "Hello World"; 
      string theHash = getHash(thePassword); 
      Console.WriteLine("String: " + thePassword); 
      Console.WriteLine("Encrypted Hash: " + theHash); 
      Console.ReadKey(true); 
     } 

     static string getHash(string password) 
     { 
      // create a ripemd160 object 
      RIPEMD160 r160 = RIPEMD160Managed.Create(); 
      // convert the string to byte 
      byte[] myByte = System.Text.Encoding.ASCII.GetBytes(password); 
      // compute the byte to RIPEMD160 hash 
      byte[] encrypted = r160.ComputeHash(myByte); 
      // create a new StringBuilder process the hash byte 
      StringBuilder sb = new StringBuilder(); 
      for (int i = 0; i < encrypted.Length; i++) 
      { 
       sb.Append(encrypted[i].ToString("X2")); 
      } 
      // convert the StringBuilder to String and convert it to lower case and return it. 
      return sb.ToString().ToLower(); 
     } 
    } 
} 
+0

如果使用'ToString(「x2」)',則不需要將其轉換爲小寫。 – Howwie