1
\$\begingroup\$

Using bouncy castle .net implementation (version: 1.8.1.0), I am trying to create an encryption key from a known master key using a key derivation function. The NIST Publication 800-108 contains recommendation for key derivation using pseudorandom functions (PRF). This document has several KDF modes defined in it. I am trying to use KDF in Counter Mode (as outlined in section 5.1). This (as other KDF modes in this spec) use PRF, which according to section 4 can be HMAC or CMAC.

Can some one please take a look at the following code and comment on the correctness of this code?

    [TestMethod]
    public void CanCreateKdfWithCounterModeUsingCmacWithAesCipher()
    {
        var masterKeyHex = "5F0D130486609AEEF68A98E7793FB7EA";  //16 bytes
        Console.WriteLine($"masterKeyHex: {masterKeyHex}");

        // Ki = PRF (s, x) where s = Key, x = [i]2 || Label || Separator || Context || [L]2
        var counterParamHex = "01";
        var labelParamHex = "000000000000000000000004";
        var seperatorParamHex = "00";
        var contexParamHex = "77FA54DE8019D742E48F4682CBE55332";
        var lParamHex = "0100";

        //x = 0x01 || 0x000000000000000000000004 || 0x00 || 0x77FA54DE8019D742E48F4682CBE55332 || 0x0100
        var xHex = counterParamHex + labelParamHex + seperatorParamHex + contexParamHex + lParamHex;

        var sBytes = Utility.HexToBytes(masterKeyHex);
        var xBytes = Utility.HexToBytes(xHex);

        IBlockCipher cipher = new AesEngine();
        ICipherParameters cipherParameters = new KeyParameter(sBytes);
        IMac mac = new CMac(cipher);
        mac.Init(cipherParameters);
        mac.BlockUpdate(xBytes, 0, xBytes.Length);

        var kIBytes = new byte[16];
        var doFinalReturn = mac.DoFinal(kIBytes, 0);

        Console.WriteLine($"doFinalReturn: {doFinalReturn}");
        Assert.AreEqual(kIBytes.Length, doFinalReturn);

        var kIHex = Utility.BytesToHex(kIBytes);
        Console.WriteLine($"kIHex: {kIHex}");
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.