問題描述
我想在 c# 中使用 Rfc2898 來派生密鑰.我還需要使用 SHA256 作為 Rfc2898 的摘要.我找到了類 Rfc2898DeriveBytes
,但它使用 SHA-1,我看不出有辦法讓它使用不同的摘要.
I want to use Rfc2898 in c# to derive a key. I also need to use SHA256 as Digest for Rfc2898. I found the class Rfc2898DeriveBytes
, but it uses SHA-1 and I don't see a way to make it use a different digest.
有沒有辦法在 c# 中使用 Rfc2898 和 SHA256 作為摘要(沒有從頭開始實現它)?
Is there a way to use Rfc2898 in c# with SHA256 as digest (short of implementing it from scratch)?
推薦答案
查看 Bruno Garcia 的回答.
See Bruno Garcia's answer.
Carsten:請接受那個答案而不是這個答案.
Carsten: Please accept that answer rather than this one.
在我開始回答這個問題時,Rfc2898DeriveBytes 無法配置為使用不同的哈希函數.但與此同時,它也得到了改進.見布魯諾加西亞的回答.以下函數可用于生成用戶提供的密碼的哈希版本,以存儲在數據庫中用于身份驗證.
At the time I started this answer, Rfc2898DeriveBytes was not configurable to use a different hash function. In the meantime, though, it has been improved; see Bruno Garcia's answer. The following function can be used to generate a hashed version of a user-provided password to store in a database for authentication purposes.
對于舊 .NET 框架的用戶,這仍然很有用:
For users of older .NET frameworks, this is still useful:
// NOTE: The iteration count should
// be as high as possible without causing
// unreasonable delay. Note also that the password
// and salt are byte arrays, not strings. After use,
// the password and salt should be cleared (with Array.Clear)
public static byte[] PBKDF2Sha256GetBytes(int dklen, byte[] password, byte[] salt, int iterationCount){
using(var hmac=new System.Security.Cryptography.HMACSHA256(password)){
int hashLength=hmac.HashSize/8;
if((hmac.HashSize&7)!=0)
hashLength++;
int keyLength=dklen/hashLength;
if((long)dklen>(0xFFFFFFFFL*hashLength) || dklen<0)
throw new ArgumentOutOfRangeException("dklen");
if(dklen%hashLength!=0)
keyLength++;
byte[] extendedkey=new byte[salt.Length+4];
Buffer.BlockCopy(salt,0,extendedkey,0,salt.Length);
using(var ms=new System.IO.MemoryStream()){
for(int i=0;i<keyLength;i++){
extendedkey[salt.Length]=(byte)(((i+1)>>24)&0xFF);
extendedkey[salt.Length+1]=(byte)(((i+1)>>16)&0xFF);
extendedkey[salt.Length+2]=(byte)(((i+1)>>8)&0xFF);
extendedkey[salt.Length+3]=(byte)(((i+1))&0xFF);
byte[] u=hmac.ComputeHash(extendedkey);
Array.Clear(extendedkey,salt.Length,4);
byte[] f=u;
for(int j=1;j<iterationCount;j++){
u=hmac.ComputeHash(u);
for(int k=0;k<f.Length;k++){
f[k]^=u[k];
}
}
ms.Write(f,0,f.Length);
Array.Clear(u,0,u.Length);
Array.Clear(f,0,f.Length);
}
byte[] dk=new byte[dklen];
ms.Position=0;
ms.Read(dk,0,dklen);
ms.Position=0;
for(long i=0;i<ms.Length;i++){
ms.WriteByte(0);
}
Array.Clear(extendedkey,0,extendedkey.Length);
return dk;
}
}
這篇關于Rfc2898/PBKDF2 與 SHA256 作為 C# 中的摘要的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!