将PCL库哈希代码重写为新的.NET标准库的问题

问题描述:

基本上,我需要重写下面的方法,它们可以在较早的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

尝试做这样的事情:可用

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