Search code examples
carrayspointersaes

shifting array elements in c for shift row in AES


I am trying to implement the shift row functionality(of AES encryption), I have written the following function but for the array elements corresponding to positions 2,3 3,2 and 3,3 are not getting exchanged correctly. Kindly have a look and advise...

expected output 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;
    }


}

Solution

  • some workaround I had to do, not perfect solution but did the job...

    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
    

    any other solution/approach would be deeply appreciated