代码之家  ›  专栏  ›  技术社区  ›  Ranhiru Jude Cooray

Bouncy Castle C中的PBKDF2#

  •  14
  • Ranhiru Jude Cooray  · 技术社区  · 14 年前

    我一直在研究C#Bouncy Castle API,以找到如何进行PBKDF2密钥派生。

    我试着通读Pkcs5S2ParametersGenerator.cs和PBKDF2Params.cs文件,但我真的不知道怎么做。

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

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

    有没有人在C#做过这件事,或者对此有什么线索?或者有人已经用Java实现了BouncyCastle并且可以提供帮助?

    提前很多时间:)

    更新: 我在蹦蹦跳跳的城堡里找到了这个方法。看看下面的答案:)

    2 回复  |  直到 14 年前
        1
  •  14
  •   Ranhiru Jude Cooray    14 年前

    经过数小时的代码检查,我发现最简单的方法是在Pkcs5S2ParametersGenerator.cs中获取部分代码,并创建自己的类,当然它使用其他bouncycastleapi。这与dotnetcompact框架(windowsmobile)完美结合。这相当于Rfc2898DeriveBytes类,Dot-Net Compact Framework 2.0/3.5中没有该类。好吧,也许不是完全等价的,但做的工作:)

    使用的PRF(伪随机函数)是HMAC-SHA1

    http://www.bouncycastle.org/csharp/ 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;
            }
    
    
        }
    }
    

    这是一个非常简单的示例,其中密码和salt由用户提供。

    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/

    如果有人得到不正确的结果,请报告:)

    希望这能帮助别人:)

    http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-00

    更新: RNGCryptoServiceProvider . 确保引用 System.Security.Cryptography 命名空间。

    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();        
    
    byte[] salt = new byte[16];
    
    rng.GetBytes(salt);
    
        2
  •  1
  •   Edwin    11 年前

    我自己也有这个问题,找到了更直接的方法。至少从BouncyCastle1.7开始,您可以这样做(在VB中使用Org.BouncyCastle.Crypto):

    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测试过了,而且还可以!