24

我想在 c# 中使用 Rfc2898 来派生密钥。我还需要使用 SHA256 作为 Rfc2898 的摘要。我找到了这个类Rfc2898DeriveBytes,但它使用 SHA-1,我没有看到让它使用不同摘要的方法。

有没有办法在 c# 中使用 Rfc2898 和 SHA256 作为摘要(没有从头开始实现它)?

4

8 回答 8

17

.NET Core 有一个新的Rfc2898DeriveBytes.

CoreFX版本不再具有硬编码的哈希算法

代码在 Github 上可用。它于 2017 年 3 月合并为 master,并随 .NET Core 2.0 一起提供。

于 2017-10-28T16:50:36.590 回答
17

对于那些需要它的人,.NET Framework 4.7.2包含允许指定散列算法的 Rfc2898DeriveBytes 重载:

byte[] bytes;
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName.SHA256))
{
    bytes = deriveBytes.GetBytes(PBKDF2SubkeyLength);
}

目前的HashAlgorithmName选项是:

  • MD5
  • SHA1
  • SHA256
  • SHA3​​84
  • SHA512
于 2018-08-04T23:39:37.773 回答
15

请参阅布鲁诺·加西亚的回答。

Carsten:请接受这个答案而不是这个答案。


在我开始这个答案时,Rfc2898DeriveBytes 无法配置为使用不同的哈希函数。但与此同时,它也得到了改进。见布鲁诺加西亚的回答。以下函数可用于生成用户提供的密码的散列版本,以存储在数据库中用于身份验证。

对于较旧的 .NET 框架的用户,这仍然很有用:

// 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;
        }
    }
于 2013-09-06T03:20:07.430 回答
7

BCLRfc2898DeriveBytes被硬编码为使用 sha-1。

KeyDerivation.Pbkdf2允许完全相同的输出,但它也允许 HMAC SHA-256 和 HMAC SHA-512。它也更快;在我的机器上大约 5 倍 - 这对安全性有好处,因为它允许更多轮次,这使得饼干的生活更加困难(顺便说一下,sha-512 对 gpu 的友好性远低于 sha-256 或 sha1)。而且 api 更简单,启动:

byte[] salt = ...
string password = ...
var rounds = 50000;                       // pick something bearable
var num_bytes_requested = 16;             // 128 bits is fine
var prf = KeyDerivationPrf.HMACSHA512;    // or sha256, or sha1
byte[] hashed = KeyDerivation.Pbkdf2(password, salt, prf, rounds, num_bytes_requested);

它来自不依赖于 asp.net 核心的 nuget 包Microsoft.AspNetCore.Cryptography.KeyDerivation ;它在 .net 4.5.1 或 .net 标准 1.3 或更高版本上运行。

于 2017-05-12T07:11:36.293 回答
2

你可以使用充气城堡。C#规范列出了算法“PBEwithHmacSHA-256”,它只能是带有SHA-256的PBKDF2。

于 2013-09-06T23:42:00.027 回答
2

我知道这是一个老问题,但是对于遇到它的任何人,您现在都可以使用 Microsoft.AspNetCore.Cryptography.KeyDerivation nuget 包中的 KeyDerivation.Pbkdf2。它是在 asp.net 核心中使用的。

不幸的是,它会添加大量不需要的引用。您可以复制代码并将其粘贴到您自己的项目中(尽管您现在必须维护作为 PITA 的加密代码)

于 2017-02-22T17:54:28.713 回答
1

值得一提的是,这里是 Microsoft 实现的副本,但将 SHA-1 替换为 SHA512:

namespace System.Security.Cryptography
{
using System.Globalization;
using System.IO;
using System.Text;

[System.Runtime.InteropServices.ComVisible(true)]
public class Rfc2898DeriveBytes_HMACSHA512 : DeriveBytes
{
    private byte[] m_buffer;
    private byte[] m_salt;
    private HMACSHA512 m_HMACSHA512;  // The pseudo-random generator function used in PBKDF2

    private uint m_iterations;
    private uint m_block;
    private int m_startIndex;
    private int m_endIndex;
    private static RNGCryptoServiceProvider _rng;
    private static RNGCryptoServiceProvider StaticRandomNumberGenerator
    {
        get
        {
            if (_rng == null)
            {
                _rng = new RNGCryptoServiceProvider();
            }
            return _rng;
        }
    }

    private const int BlockSize = 20;

    //
    // public constructors 
    // 

    public Rfc2898DeriveBytes_HMACSHA512(string password, int saltSize) : this(password, saltSize, 1000) { }

    public Rfc2898DeriveBytes_HMACSHA512(string password, int saltSize, int iterations)
    {
        if (saltSize < 0)
            throw new ArgumentOutOfRangeException("saltSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));

        byte[] salt = new byte[saltSize];
        StaticRandomNumberGenerator.GetBytes(salt);

        Salt = salt;
        IterationCount = iterations;
        m_HMACSHA512 = new HMACSHA512(new UTF8Encoding(false).GetBytes(password));
        Initialize();
    }

    public Rfc2898DeriveBytes_HMACSHA512(string password, byte[] salt) : this(password, salt, 1000) { }

    public Rfc2898DeriveBytes_HMACSHA512(string password, byte[] salt, int iterations) : this(new UTF8Encoding(false).GetBytes(password), salt, iterations) { }

    public Rfc2898DeriveBytes_HMACSHA512(byte[] password, byte[] salt, int iterations)
    {
        Salt = salt;
        IterationCount = iterations;
        m_HMACSHA512 = new HMACSHA512(password);
        Initialize();
    }

    //
    // public properties 
    //

    public int IterationCount
    {
        get { return (int)m_iterations; }
        set
        {
            if (value <= 0)
                throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
            m_iterations = (uint)value;
            Initialize();
        }
    }

    public byte[] Salt
    {
        get { return (byte[])m_salt.Clone(); }
        set
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (value.Length < 8)
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Cryptography_PasswordDerivedBytes_FewBytesSalt")));
            m_salt = (byte[])value.Clone();
            Initialize();
        }
    }

    // 
    // public methods
    // 

    public override byte[] GetBytes(int cb)
    {
        if (cb <= 0)
            throw new ArgumentOutOfRangeException("cb", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
        byte[] password = new byte[cb];

        int offset = 0;
        int size = m_endIndex - m_startIndex;
        if (size > 0)
        {
            if (cb >= size)
            {
                Buffer.InternalBlockCopy(m_buffer, m_startIndex, password, 0, size);
                m_startIndex = m_endIndex = 0;
                offset += size;
            }
            else
            {
                Buffer.InternalBlockCopy(m_buffer, m_startIndex, password, 0, cb);
                m_startIndex += cb;
                return password;
            }
        }

        //BCLDebug.Assert(m_startIndex == 0 && m_endIndex == 0, "Invalid start or end index in the internal buffer.");

        while (offset < cb)
        {
            byte[] T_block = Func();
            int remainder = cb - offset;
            if (remainder > BlockSize)
            {
                Buffer.InternalBlockCopy(T_block, 0, password, offset, BlockSize);
                offset += BlockSize;
            }
            else
            {
                Buffer.InternalBlockCopy(T_block, 0, password, offset, remainder);
                offset += remainder;
                Buffer.InternalBlockCopy(T_block, remainder, m_buffer, m_startIndex, BlockSize - remainder);
                m_endIndex += (BlockSize - remainder);
                return password;
            }
        }
        return password;
    }

    public override void Reset()
    {
        Initialize();
    }

    private void Initialize()
    {
        if (m_buffer != null)
            Array.Clear(m_buffer, 0, m_buffer.Length);
        m_buffer = new byte[BlockSize];
        m_block = 1;
        m_startIndex = m_endIndex = 0;
    }
    internal static byte[] Int(uint i)
    {
        byte[] b = BitConverter.GetBytes(i);
        byte[] littleEndianBytes = { b[3], b[2], b[1], b[0] };
        return BitConverter.IsLittleEndian ? littleEndianBytes : b;
    }
    // This function is defined as follow : 
    // Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i)
    // where i is the block number. 
    private byte[] Func()
    {
        byte[] INT_block = Int(m_block);

        m_HMACSHA512.TransformBlock(m_salt, 0, m_salt.Length, m_salt, 0);
        m_HMACSHA512.TransformFinalBlock(INT_block, 0, INT_block.Length);
        byte[] temp = m_HMACSHA512.Hash;
        m_HMACSHA512.Initialize();

        byte[] ret = temp;
        for (int i = 2; i <= m_iterations; i++)
        {
            temp = m_HMACSHA512.ComputeHash(temp);
            for (int j = 0; j < BlockSize; j++)
            {
                ret[j] ^= temp[j];
            }
        }

        // increment the block count.
        m_block++;
        return ret;
    }
}
}

除了用替换外HMACSHA1HMACSHA512还需要添加StaticRandomNumberGenerator属性,因为Utils.StaticRandomNumberGeneratorinternal在微软程序集中,需要添加static byte[] Int(uint i)方法,因为微软Utils.Int也是internal。除此之外,代码有效。

于 2015-12-24T16:10:11.477 回答
0

虽然这是一个老问题,但因为我在我的 Question Configurable Rfc2898DeriveBytes中添加了对这个问题的引用,我在其中询问了Rfc2898DeriveBytes算法的通用实现是否正确。

我现在已经测试并验证了它是否会生成完全相同的哈希值,如果HMACSHA1TAlgorithm作为 .NET 实现提供的话Rfc2898DeriveBytes

为了使用该类,必须为需要字节数组作为第一个参数的 HMAC 算法提供构造函数。

例如:

var rfcGenSha1 = new Rfc2898DeriveBytes<HMACSHA1>(b => new HMACSHA1(b), key, ...)
var rfcGenSha256 = new Rfc2898DeriveBytes<HMACSHA256>(b => new HMACSHA256(b), key, ...)

这需要算法在这一点上继承 HMAC,我相信只要算法的构造函数接受构造函数的字节数组,就可以减少要求继承的限制,KeyedHashAlgorithm而不是。HMAC

于 2016-03-30T13:01:06.343 回答