2017-09-02 27 views
1

基本上,我需要重寫下面的方法,它們可以在較早的PCL庫項目中使用,但不能在.NET標準庫中使用。將PCL庫哈希代碼重寫爲新的.NET標準庫的問題

public static string GenerateSalt() 
    { 
     var buf = new byte[16]; 
     (new RNGCryptoServiceProvider()).GetBytes(buf); 
     return Convert.ToBase64String(buf); 
    } 

    public static string GenerateHash(string password, string salt) 
    { 
     byte[] bytes = Encoding.Unicode.GetBytes(password); 
     byte[] src = Convert.FromBase64String(salt); 
     byte[] dst = new byte[src.Length + bytes.Length]; 

     System.Buffer.BlockCopy(src, 0, dst, 0, src.Length); 
     System.Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); 
     HashAlgorithm algorithm = HashAlgorithm.Create("SHA1"); 
     byte[] inArray = algorithm.ComputeHash(dst); 
     return Convert.ToBase64String(inArray); 
    } 

到目前爲止,我已經嘗試做用RandomNumberGenerator.Create()RandomNumberGenerator.GetBytes()方法沒有成功的進展。

遇到錯誤解釋RandomNumberGenerator是一個接口,因此沒有實例可以創建(這是可以理解的),但我想,必須有一種方式(我不是很在.net & C#經歷) 。

+0

嗨,這.NET標準的版本,你定位? – Kostya

+0

@KostyaK版本1.4 – developer10

回答

1

嘗試做這樣的事情:可用

public static string GenerateSalt() 
    { 
     var buf = new byte[16]; 
     RandomNumberGenerator.Create().GetBytes(buf); 
     return Convert.ToBase64String(buf); 
    } 

    public static string GenerateHash(string password, string salt) 
    { 
     byte[] bytes = Encoding.Unicode.GetBytes(password); //TODO: consider removing it 
     byte[] src = Convert.FromBase64String(salt); 
     byte[] dst = new byte[src.Length + bytes.Length]; 

     System.Buffer.BlockCopy(src, 0, dst, 0, src.Length); 
     System.Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); 

     var provider = new Rfc2898DeriveBytes(password, src, 1000); 
     byte[] inArray = provider.GetBytes(20/*bytes like in SHA-1*/); 

     return Convert.ToBase64String(inArray); 
    } 

或檢查其他API 1.4版本here

+0

謝謝。你可以看看最新的方法和線路(新的RNGCryptoServiceProvider())。GetBytes(buf);' - 我該如何處理?我想它會起作用,所以我可以接受你的答案。 – developer10

+0

@ developer10試試這個。不過,請仔細測試一下,看看它是否適用於您。 – Kostya

+0

我已經設法自己做到了。由於第二種方法,我會接受你的答案。謝謝! – developer10