在Bouncy Castle C#中的PBKDF2

15

我一直在尝试使用C#的Bouncy Castle API找到如何进行PBKDF2密钥派生。

但目前我真的一无所知。

我曾尝试阅读Pkcs5S2ParametersGenerator.cs和PBKDF2Params.cs文件,但我真的无法弄清楚该如何做。

根据我迄今为止所做的研究,PBKDF2需要一个字符串(或char[]),即密码、盐和迭代次数。

到目前为止,最有前途且最明显的是PBKDF2Params和Pkcs5S2ParametersGenerator。

但这些都似乎不接受字符串或char[]。

有没有人在C#中完成了这个过程或者对此有任何线索? 或者有谁已经在Java中实现了BouncyCastle并可以提供帮助吗?

先谢谢大家 :)

更新: 我已经找到了如何在Bouncy Castle中实现此操作。请参见下面的答案 :)

2个回答

14
经过数小时的代码研究,我发现最简单的方法是从Pkcs5S2ParametersGenerator.cs中获取几个代码部分,并创建自己的类,当然要使用其他BouncyCastle API。这在Dot Net Compact Framework(Windows Mobile)上完美运行。这相当于Rfc2898DeriveBytes类,在Dot Net Compact Framework 2.0/3.5中不存在。也许并不是完全等价,但是能胜任任务 :)
这是PKCS5/PKCS#5。
使用的PRF(伪随机函数)将是HMAC-SHA1。
首先,从http://www.bouncycastle.org/csharp/下载已编译的Bouncy Castle程序集,并将BouncyCastle.Crypto.dll添加为项目的引用。
然后创建一个新的类文件,其中包含以下代码。
using System;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;

namespace PBKDF2_PKCS5
{
    class PBKDF2
    {

        private readonly IMac hMac = new HMac(new Sha1Digest());

        private void F(
            byte[] P,
            byte[] S,
            int c,
            byte[] iBuf,
            byte[] outBytes,
            int outOff)
        {
            byte[] state = new byte[hMac.GetMacSize()];
            ICipherParameters param = new KeyParameter(P);

            hMac.Init(param);

            if (S != null)
            {
                hMac.BlockUpdate(S, 0, S.Length);
            }

            hMac.BlockUpdate(iBuf, 0, iBuf.Length);

            hMac.DoFinal(state, 0);

            Array.Copy(state, 0, outBytes, outOff, state.Length);

            for (int count = 1; count != c; count++)
            {
                hMac.Init(param);
                hMac.BlockUpdate(state, 0, state.Length);
                hMac.DoFinal(state, 0);

                for (int j = 0; j != state.Length; j++)
                {
                    outBytes[outOff + j] ^= state[j];
                }
            }
        }

        private void IntToOctet(
            byte[] Buffer,
            int i)
        {
            Buffer[0] = (byte)((uint)i >> 24);
            Buffer[1] = (byte)((uint)i >> 16);
            Buffer[2] = (byte)((uint)i >> 8);
            Buffer[3] = (byte)i;
        }

        // Use this function to retrieve a derived key.
        // dkLen is in octets, how much bytes you want when the function to return.
        // mPassword is the password converted to bytes.
        // mSalt is the salt converted to bytes
        // mIterationCount is the how much iterations you want to perform. 
        

        public byte[] GenerateDerivedKey(
            int dkLen,
            byte[] mPassword,
            byte[] mSalt,
            int mIterationCount
            )
        {
            int hLen = hMac.GetMacSize();
            int l = (dkLen + hLen - 1) / hLen;
            byte[] iBuf = new byte[4];
            byte[] outBytes = new byte[l * hLen];

            for (int i = 1; i <= l; i++)
            {
                IntToOctet(iBuf, i);

                F(mPassword, mSalt, mIterationCount, iBuf, outBytes, (i - 1) * hLen);
            }

        //By this time outBytes will contain the derived key + more bytes.
       // According to the PKCS #5 v2.0: Password-Based Cryptography Standard (www.truecrypt.org/docs/pkcs5v2-0.pdf) 
       // we have to "extract the first dkLen octets to produce a derived key".

       //I am creating a byte array with the size of dkLen and then using
       //Buffer.BlockCopy to copy ONLY the dkLen amount of bytes to it
       // And finally returning it :D

        byte[] output = new byte[dkLen];

        Buffer.BlockCopy(outBytes, 0, output, 0, dkLen);

        return output;
        }


    }
}

如何使用这个函数?很简单! :) 以下是一个非常简单的示例,其中密码和盐由用户提供。

private void cmdDeriveKey_Click(object sender, EventArgs e)
        {
            byte[] salt = ASCIIEncoding.UTF8.GetBytes(txtSalt.Text);

            PBKDF2 passwordDerive = new PBKDF2();
            

      // I want the key to be used for AES-128, thus I want the derived key to be
      // 128 bits. Thus I will be using 128/8 = 16 for dkLen (Derived Key Length) . 
      //Similarly if you wanted a 256 bit key, dkLen would be 256/8 = 32. 

            byte[] result = passwordDerive.GenerateDerivedKey(16, ASCIIEncoding.UTF8.GetBytes(txtPassword.Text), salt, 1000);

           //result would now contain the derived key. Use it for whatever cryptographic purpose now :)
           //The following code is ONLY to show the derived key in a Textbox.

            string x = "";

            for (int i = 0; i < result.Length; i++)
            {
                x += result[i].ToString("X");
            }

            txtResult.Text = x;

        }
如何检查这是否正确? 有一个在线的PBKDF2 JavaScript实现 http://anandam.name/pbkdf2/ 我得到了一致的结果 :) 如果有人得到不正确的结果,请报告 :) 希望这能帮助到某个人 :) 更新:在此提供的测试向量下已确认可工作。 https://datatracker.ietf.org/doc/html/draft-josefsson-pbkdf2-test-vectors-00 更新: 或者,可以使用 RNGCryptoServiceProvider 作为盐。请确保引用 System.Security.Cryptography 命名空间。
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();        
            
byte[] salt = new byte[16];

rng.GetBytes(salt);

1
你回答自己的问题非常快! - President James K. Polk
1
你刚刚为我节省了很多时间。谢谢! - John
@John:很高兴能提供任何帮助 :) - Ranhiru Jude Cooray
你应该看看Edwin的代码。如果存在一个或多个漏洞,使用上述代码就不太安全了... - Michael Seifert

3

我曾经也遇到过这个问题,找到了一种更直接的方法。至少在Bouncy Castle 1.7版本中,您可以像下面这样做(使用Org.BouncyCastle.Crypto的VB代码):

Dim bcKeyDer As New Generators.Pkcs5S2ParametersGenerator()
bcKeyDer.Init(password, salt, keyIterations)
Dim bcparam As Parameters.KeyParameter = bcKeyDer.GenerateDerivedParameters("aes256", 256)
Dim key1() As Byte = bcparam.GetKey()

我已经将其与.NET的System.Security.Cryptography进行了测试,它有效!


非常有帮助,谢谢。我相信你可以将算法作为参数添加在这里Pkcs5S2ParametersGenerator(new Org.BouncyCastle.Crypto.Digests.Sha256Digest()); - Michael Seifert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接