Esempio n. 1
0
        static public int Diversification_AES128(byte[] base_key, byte[] diversification_input, int diversification_lenght, ref byte[] diversified_key)
        {
            int i = 0;

            byte[] M    = new byte[32];
            bool   padd = false;

            // prepare the padding
            init(base_key);
#if _DEBUG_DIVERSIFICATION
            LogManager.DoLogOperation(string.Format("TEST K0={0}", BinConvert.ToHex(cmac_subkey_0)));
            LogManager.DoLogOperation(string.Format("TEST K1={0}", BinConvert.ToHex(cmac_subkey_1)));
            LogManager.DoLogOperation(string.Format("TEST K2={0}", BinConvert.ToHex(cmac_subkey_2)));
#endif

            // add the div constant at the beginning of M
            M[0] = 0x01;
            for (i = 0; i < diversification_lenght; i++)
            {
                M[1 + i] = diversification_input[i];
            }
            i++;

            // add the padding
            if (((i % 32) != 0) && (i < 32))
            {
                M[i] = 0x80;
                i++;
                for (; i < 32; i++)
                {
                    M[i] = 0x00;
                }
                padd = true;
            }
#if _DEBUG_DIVERSIFICATION
            LogManager.DoLogOperation(string.Format("CMAC Input D={0}", BinConvert.ToHex(M, 32)));
#endif

            /* XOR the last 16 bytes with CMAC_SubKey */
            for (i = 0; i < 16; i++)
            {
                if (padd)
                {
                    M[16 + i] ^= cmac_subkey_2[i];
                }
                else
                {
                    M[16 + i] ^= cmac_subkey_1[i];
                }
            }


#if _DEBUG_DIVERSIFICATION
            LogManager.DoLogOperation(string.Format("XOR the last 16 bytes with CMAC_SubKey2={0}", BinConvert.ToHex(M, 32)));
            int lsize = 32;
#endif

            byte[] IV = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };


            /* Encryption using M */
            byte[] result = AES_Encrypt(M, base_key, IV);

#if _DEBUG_DIVERSIFICATION
            LogManager.DoLogOperation(string.Format("Encryption using M={0}", BinConvert.ToHex(M, lsize)));
#endif

            for (i = 0; i < 16; i++)
            {
                diversified_key[i] = result[16 + i];
            }

#if _DEBUG_DIVERSIFICATION
            LogManager.DoLogOperation(string.Format("Diversification key={0}", BinConvert.ToHex(diversified_key, 16)));
#endif

            return(0);
        }