2012-05-29 131 views
6

我有一個類,使用salted散列加密密碼。不能隱式地將類型字符串轉換爲字節[]

但是如果我要一個空傳遞給該類我得到以下錯誤:Cannot implicitly convert type string to byte[]

下面是類代碼:

public class MyHash 
{ 
    public static string ComputeHash(string plainText, 
          string hashAlgorithm, byte[] saltBytes) 
    { 
     Hash Code 
    } 
} 

當我使用類我得到的錯誤:「無法隱式轉換string類型爲byte []」

//Encrypt Password 
byte[] NoHash = null; 
byte[] encds = MyHash.ComputeHash(Password, "SHA256", NoHash); 
+0

'string's應該可以轉換爲'byte []'? –

回答

0

ComputeHash函數的返回類型是一個字符串。您嘗試將函數的結果分配給encds,即byte []。編譯器將這種差異指向你,因爲沒有從字符串到字節[]的隱式轉換。

+0

這是工作時間過長時發生的情況。 – MataHari

14

這是因爲你的‘ComputeHash’方法返回一個字符串,並且你想這個返回值賦給一個字節與...一起

byte[] encds = MyHash.ComputeHash(Password, "SHA256", NoHash); 

沒有 converstion,因爲存在許多不同的編碼來表示一個字符串作爲字節,如ASCII或UTF8字符串爲byte []。

您需要明確使用適當的編碼類來轉換字節,如下所示;

string x = "somestring"; 
byte[] y = System.Text.Encoding.UTF8.GetBytes(x); 
相關問題