实施AES密钥计划

时间:2013-11-19 00:34:17

标签: c++ aes

我目前正在用C ++实现AES,但是我遇到了算法的密钥扩展部分的问题。我的函数将128位密钥作为一个参数,并将扩展密钥放在作为第二个参数传递的数组中:

void Expand(const unsigned char input[16], unsigned char output[16*11])
{
    unsigned int i;
    unsigned int j;
    unsigned int t;
    for(i = 0; i < 16; i++)
    {
        output[i] = input[i];
    }
    for(i = 1; i < 11; i++)
    {
        j = i*16;
        cout << std::dec << i << ", " << j << endl;
        t = *(unsigned int*)(output + j - sizeof(unsigned int));

        //Key schedule core

        cout << std::hex << "0x" << t << " ";
        t = (t >> 8) | (t << 24);
        cout << "0x" << t << " ";
        ((unsigned char*) &t)[0] = sbox[((unsigned char*) &t)[0]];
        ((unsigned char*) &t)[1] = sbox[((unsigned char*) &t)[1]];
        ((unsigned char*) &t)[2] = sbox[((unsigned char*) &t)[2]];
        ((unsigned char*) &t)[3] = sbox[((unsigned char*) &t)[3]];
        ((unsigned char*) &t)[0] ^= rcon[i];

        cout << "0x" << t << " ";

        //First column of current round key
        t ^= *(unsigned int*)(output + j - 4*sizeof(unsigned int));
        *(unsigned int*)(output + j) = t;

        cout << "0x" << t << " ";

        //Second column of current round key
        t ^= *(unsigned int*)(output + j - 3*sizeof(unsigned int));
        *(unsigned int*)(output + j + 1*sizeof(unsigned int)) = t;

        cout << "0x" << t << " ";

        //Third column of current round key
        t ^= *((unsigned int*)output + j - 2*sizeof(unsigned int));
        *(unsigned int*)(output + j + 2*sizeof(unsigned int)) = t;

        cout << "0x" << t << " ";

        //Fourth column of current round key
        t ^= *(unsigned int*)(output + j - 1*sizeof(unsigned int));
        *(unsigned int*)(output + j + 3*sizeof(unsigned int)) = t;

        cout << "0x" << t << endl;
    }
}

我一直在使用description on Wikipedia来指导我完成算法本身。但是,我一直遇到一个奇怪的问题,我似乎无法追踪:输出中的前24个字节是正确的(包括原始密钥中的16个字节),但是在24字节标记之后的其他所有内容是不正确的。我一直在使用this page上的关键扩展“测试向量”。我可能正在看一些愚蠢的错误,但我无法发现它。任何帮助表示赞赏。 (顺便说一句,函数中的文本输出只是用于调试)

编辑: 所以我通过完全重写第二个循环使我的函数工作更明确:

    j = i*16;

    t[0] = sbox[output[j-3]] ^ rcon[i];
    t[1] = sbox[output[j-2]];
    t[2] = sbox[output[j-1]];
    t[3] = sbox[output[j-4]];

    output[j] = output[j-16] ^ t[0];
    output[j+1] = output[j-15] ^ t[1];
    output[j+2] = output[j-14] ^ t[2];
    output[j+3] = output[j-13] ^ t[3];

    output[j+4] = output[j-12] ^ output[j];
    output[j+5] = output[j-11] ^ output[j+1];
    output[j+6] = output[j-10] ^ output[j+2];
    output[j+7] = output[j-9] ^ output[j+3];

    output[j+8] = output[j-8] ^ output[j+4];
    output[j+9] = output[j-7] ^ output[j+5];
    output[j+10] = output[j-6] ^ output[j+6];
    output[j+11] = output[j-5] ^ output[j+7];

    output[j+12] = output[j-4] ^ output[j+8];
    output[j+13] = output[j-3] ^ output[j+9];
    output[j+14] = output[j-2] ^ output[j+10];
    output[j+15] = output[j-1] ^ output[j+11];

其中t是4号无符号字符数组。但是,我似乎仍然无法理解为什么我的其他代码不正确。有什么建议吗?

0 个答案:

没有答案