24

C# で Rfc2898 を使用してキーを取得したいと考えています。また、Rfc2898 のダイジェストとして SHA256 を使用する必要があります。class を見つけましたRfc2898DeriveBytesが、SHA-1 を使用しており、別のダイジェストを使用する方法がわかりません。

SHA256 を使用して C# で Rfc2898 をダイジェストとして使用する方法はありますか (スクラッチから実装することはできません)。

4

8 に答える 8

15

Bruno Garcia の回答を参照してください。

Carsten: この回答ではなく、その回答を受け入れてください。


この回答を開始した時点では、Rfc2898DeriveBytes は別のハッシュ関数を使用するように構成できませんでした。ただし、その間は改善されています。Bruno Garcia の回答を参照してください。次の関数を使用して、ユーザー提供のパスワードのハッシュ バージョンを生成し、認証目的でデータベースに格納できます。

古い .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 に答える
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;
    }
}
}

に置き換えるだけHMACSHA1でなく、はmicrosoft アセンブリにあるためプロパティHMACSHA512を追加する必要があり、microsoftもであるためメソッドを追加する必要があります。それ以外は、コードは機能します。StaticRandomNumberGeneratorUtils.StaticRandomNumberGeneratorinternalstatic byte[] Int(uint i)Utils.Intinternal

于 2015-12-24T16:10:11.477 に答える
0

これは古い質問ですが、質問構成可能 Rfc2898DeriveBytesRfc2898DeriveBytesでこの質問への参照を追加したため、アルゴリズムの一般的な実装が正しいかどうかを尋ねました。

の.NET実装としてHMACSHA1提供されている場合、まったく同じハッシュ値を生成することをテストおよび検証しましたTAlgorithmRfc2898DeriveBytes

クラスを使用するには、最初の引数としてバイト配列を必要とする 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 に答える