在c中移位数组元素以用于AES中的移位行

时间:2014-03-17 18:42:33

标签: c arrays pointers aes

我正在尝试实现移位行功能(AES加密),我编写了以下函数,但是对应于位置2,3 3,2和3,3的数组元素未正确交换。请看看并建议...

预期输出http://en.wikipedia.org/wiki/File:AES-ShiftRows.svg

void shiftRow(unsigned char **state){

int i,j,n; unsigned char *temp;

    temp =(unsigned char *)malloc(sizeof(unsigned char));

    for(i=1;i<4;i++){
        *temp =state[i][0];
        printf("\t%x",*temp);
        for(j=0;j<4;j++){
            n = ((i+j)>3?(i+j)-4:i+j);
            state[i][j]=state[i][n];
        }
        printf("\t%x\n",*temp);
        state[i][j-i]=*temp;
    }


}

3 个答案:

答案 0 :(得分:0)

我必须做的一些解决方法,不是完美的解决方案,而是完成了工作......

void shiftRow(unsigned char **state){
    int i,j,n; unsigned char temp;

    //  temp =(unsigned char *)malloc(sizeof(unsigned char));

        for(i=1;i<2;i++){
            temp =state[i][0];
            //printf("\t%x",temp);
            for(j=0;j<4;j++){
                n = ((i+j)>3?(i+j)-4:i+j);
                state[i][j]=state[i][n];        
            }
            printf("\t%x\n",temp);
            state[i][j-i]=temp;

        }

            temp =state[2][0];
            state[2][0]=state[2][2];
            state[2][2]=temp;
            temp =state[2][1];
            state[2][1]=state[2][3];
            state[2][3]=temp;

            temp =state[3][0];
            state[3][0]=state[3][3];
            state[3][3]=state[3][2];
            state[3][2]=state[3][1];
            state[3][1]=temp;

    } //shiftrow ends

任何其他解决方案/方法都将深受赞赏

答案 1 :(得分:0)

我是怎么做到的。也许对某人有帮助。

void AES::shiftRows(byte state[4][4])
{
    int sub = 1;    // the subtraction of numCol
    byte tmp, tmp1, tmp2;

    for (int numRow = 1; numRow < 4; numRow++)
    {
        tmp = state[numRow][0];

        if (sub == 2) {
            tmp1 = state[numRow][1];
        }
        else if (sub == 3)
        {
            tmp1 = state[numRow][1];
            tmp2 = state[numRow][2];
        }

        for (int numCol = 1; numCol < 4; numCol++) {
            if (numCol - sub >= 0)
            {
                state[numRow][numCol - sub] = state[numRow][numCol];        // be careful don´t go out of range
            }
        }

        if (sub == 1) {
            state[1][3] = tmp;
        }
        else if (sub == 2) {
            state[2][2] = tmp;
            state[2][3] = tmp1;
        }
        else if (sub == 3)
        {
            state[3][1] = tmp;
            state[3][2] = tmp1;
            state[3][3] = tmp2;
        }
        sub++;
    }
}

答案 2 :(得分:0)

所以这是我在移动它之前的向量。

这个向量 [0 .. 15]

std::vector n_S_BOX = [63 c0 ab 20 eb 2f 30 cb 9f 93 af 2b a0 92 c7 a2]

    int five = 5;
    for(int i = 0; i < 16; i += 4)
    {
            for(int t = 0; t < 4; ++t)
            {
                    shift_Rows_V.push_back(n_S_BOX[(i + five*t)%16]);
            }
    }

为此 [63 2f af a2 eb 93 c7 20 9f 92 ab cb a0 c0 30 2b]