十六进制矩阵乘法结果不正确

时间:2018-05-23 04:28:43

标签: c++11 hex codeblocks matrix-multiplication

矩阵1:

  

0x02 0x03 0x01 0x01

     

0x01 0x02 0x03 0x01

     

0x01 0x01 0x02 0x03

     

0x03 0x01 0x01 0x02

矩阵2:

  

0x63 0x53 0xe0 0x8c

     

0x09 0x60 0xe1 0x04

     

0xcd 0x70 0xb7 0x51

     

0xba 0xca 0xd0 0xe7

这两个矩阵在这个函数中是多重的:

void mul(uint8_t state[4][4])
{
    for(unsigned short i = 0; i < 4; i++)
    {
        state [0][i] = byteProduct(0x02 ,state[0][i]) ^ byteProduct(0x03, state[1][i]) ^ state[2][i] ^ state[3][i];
        state [1][i] = state[0][i] ^ byteProduct(0x02, state[1][i]) ^ byteProduct(0x03, state[2][i]) ^ state[3][i];
        state [2][i] = state[0][i] ^ state[1][i] ^ byteProduct(0x02, state[2][i]) ^ byteProduct(0x03, state[3][i]);
        state [3][i] = byteProduct(0x03, state[0][i]) ^ state[1][i] ^ state[2][i] ^ byteProduct(0x02, state[3][i]);
    }
}

在这个函数中,我逐列地采用矩阵2,并分别乘以矩阵1的行的值。并且值应该在状态矩阵中替换。

ByteProduct定义为:

uint8_t byteProduct(uint8_t x, uint8_t y)
{
    uint8_t result = 0, temp;

    while(x != 0)
    {
        if((x & 1) != 0)
            result ^= y;

        temp = y & 0x80;
        y <<= 1;

        if(temp != 0)
            y ^= 0x1b;

        x >>= 1;
    }

    return result;
}

结果应为:

  

0x5f 0x72 0x64 0x15

     

0x57 0xf5 0xbc 0x92

     

0xf7 0xbe 0x3b 0x29

     

0x1d 0xb9 0xf9 0x1a

但该功能产生的母线与此不同。
任何解决方案吗?

请注意,这些计算是在GF(2 ^ 8)字段中执行的,因此请勿尝试使用+*运算符,而^用于{ {1}}运算符和+函数返回byteProduct() s的乘法。

我已经执行了行x列乘法。

1 个答案:

答案 0 :(得分:1)

请勿将值填充到您仍用于计算的其中一个矩阵中 首先复制它或填写新矩阵 否则,您将损害仍用于计算的值。

E.g。

    state [0][i] = byteProduct(0x02 ,state[0][i]) ^ byteProduct(0x03, state[1][i]) ^ state[2][i] ^ state[3][i];
    state [1][i] = state[0][i] ^ byteProduct(0x02, state[1][i]) ^ byteProduct(0x03, state[2][i]) ^ state[3][i];

第一行已经覆盖state [0][i]的值,然后第二行再次使用它来计算state [1][i]

相关问题