torayeff
torayeff

Reputation: 9702

AES mixColumns error

Now I am learning cryptograpgy. So, (for practice and for fun), I have decided to implement AES. I got stuck in one point (mixing columns here is my code):

typedef vector< vector<short> > vvector;

short mixBox[4][4] = 
{
    {0x02, 0x03, 0x01, 0x01},
    {0x01, 0x02, 0x03, 0x01},
    {0x01, 0x01, 0x02, 0x03},
    {0x03, 0x01, 0x01, 0x02}
};

short gfMultiply(short h1, short h2)
{
    //h1 can 0x01, 0x02 or 0x03
}

void mixColumns(vvector & v)
{
    vvector res(v.begin(), v.end());
    for(int i=0; i<4; i++)
        for(int j=0; j<4; j++)
            v[i][j] = 0x00;

    for(int i=0; i<4; i++)
        for(int j=0; j<4; j++)
            for(int k=0; k<4; k++)
                v[i][j] = v[i][j] ^ gfMultiply(mixBox[i][k], res[k][j]);
}

Theoretically, I understood multiplication gf(2^8), but for implementing algorithm, i have problems. I referred to this site. But either I can not understand some point or I am doing something wrong. In wikipedia I have read this:

"The multiplication operation is defined as: multiplication by 1 means no change, multiplication by 2 means shifting to the left, and multiplication by 3 means shifting to the left and then performing xor with the initial unshifted value. After shifting, a conditional xor with 0x1B should be performed if the shifted value is larger than 0xFF."

Assuming above I have implemented this:

short gfMultiply(short h1, short h2)
{
    //h1 can 0x01, 0x02 or 0x03
    short r;
    if(h1==0x01)
        return h2;
    if(h1==0x02)
        r = (h2<<1);
    else
        r = (h2<<1)^h2;
    if(r>0xFF)
        r = r^0x1b;
    return r;
}

But results are incorrect, when I am testing. What I am doing wrong here?

Upvotes: 2

Views: 1853

Answers (1)

torayeff
torayeff

Reputation: 9702

Sorry, for bug. I have fixed it by myself, this is the correct one:

short gfMultiply(short h1, short h2)
{
    //h1 can 0x01, 0x02 or 0x03
    short r;
    if(h1==0x01)
        return h2;
    if(h1==0x02)
    {
        r = (h2<<1);
        if(r>0xFF)
            r = r^0x11b;
    }
    else
    {
        r = (h2<<1);
        if(r>0xFF)
            r = r^0x11b;
        r = r^h2;
    }
    return r;
}

Upvotes: 3

Related Questions