在C#中将一维数组转换为二维数组用于AES数据矩阵

3

我正在尝试从一维数组中创建一个二维数组,以在Rijndael或AES加密过程中生成数据状态。我一直在尝试使用以下代码;

public byte[,] MakeAState(byte[] block){
byte[,] State;

foreach (byte i in block)
    for (int row = 0; row < 4; row++)
        for (int column = 0; column < 4; column++)
            State[column, row] = i;

return State;
}

我打算让结果变成这样

//Original Sequence
[99 111 98 97 112 97 115 115 99 111 98 97 112 97 115 115]

//Desired Sequence
[99 112 99 112]
[111 97 111 97]
[98 115 98 115]
[97 115 97 115]

结果总是出现似乎使用Block元素作为State数组的索引,导致出现“越界”错误消息。有什么办法可以解决这个问题吗?


@FlorianSchmidinger 是的,我认为是这样。请提醒我哪个部分还没有完成 :) - undip_student
@FlorianSchmidinger 非常感谢您的纠正,我在询问此事时有些匆忙。 - undip_student
我们都有时候很匆忙。 - Florian Schmidinger
2个回答

3
您可能在 State[column, row] = i; 中颠倒了 rowcolumn,这可能是导致您的越界异常的原因。不过,如果没有更多关于变量的信息,就无法确定。
但这并不是唯一的问题。假设您只想将数组分成四组。如果您翻转 row/column 并解决了异常,那么这就是您当前的情况。
//Original sequence: 
[0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15]

//Desired sequence:
[0  4  8  12]
[1  5  9  13]
[3  6  10 14]
[4  7  11 15]

//What you are currently getting:
[15 15 15 15]
[15 15 15 15]
[15 15 15 15] //<-- Last value of original sequence, everywhere.

你的代码中发生的情况是将Block中的每个位置放置在新数组的每个位置上,这意味着当算法完成时,你将得到一个填满了Block最后一个值的数组。
如果将其更改为以下内容,则可以返回所需结果。
public static byte[,] State(byte[] Block)
{
    if (Block.Length % 16 != 0)
        throw new Exception("Byte array length must be divisible by 16.");

    var rowCount = Block.Length / 4;
    var State = new byte[rowCount, 4];

    for (int column = 0, block = 0; column < 4; column++)
        for (int row = 0; row < rowCount; row++, block++)
            State[row, column] = Block[block];

    return State;
}

@undip_student 我更新了我的答案。 - Hjalmar Z

3

这应该是你想要的,它使用除法和取模来确定列和行(如果你想将矩阵转换,只需将“i%4”替换为“i / 4”):

class Program
{
    static void Main(string[] args)
    {
        byte[] original = new byte[] { 99, 111, 98, 97, 112, 97, 115, 115, 99, 111, 98, 97, 112, 97, 115, 115 };
        byte[,] result = MakeAState(original);

        for (int row = 0; row < 4; row++)
        {
            for (int column = 0; column < 4; column++)
            {
                Console.Write(result[row,column] + "   ");
            }
            Console.WriteLine();
        }


    }

    public static byte[,] MakeAState(byte[] block)
    {
        if (block.Length < 16)
        {
            return null;
        }

        byte[,] state = new byte[4,4];

        for (int i = 0; i < 16; i++)
        {
            state[i % 4, i / 4] = block[i];
        }

        return state;
    }
}

}

输出:

99 112 99 112

111 97 111 97

98 115 98 115

97 115 97 115


我喜欢[模数,除法]索引,看起来很流畅。我会在未来借鉴它 :) - Hjalmar Z
@HjalmarZ 不需要偷了...我免费送给你了! - Florian Schmidinger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接