使用c#对输入块密码进行System.IndexOutOfRangeException

时间:2015-10-24 09:20:17

标签: c# encryption cryptography indexoutofboundsexception block-cipher

我尝试将二进制输入写入256位长的块密码,并使用自己的模式。

使用输入类

private string inputBinary(string binary_, string rule)
{
    var positionArray = rule.Split("\t\r\n, ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
    char[]  result_ = new char[256];

    for (int i = 0; i < binary_.Length; i++)
    {
        int position = int.Parse(positionArray[i]);
        result_[position] = binary_[i];
    }
    return new string(result_);
}

有规则

input_plain[0] = "60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 16, 59, 75, 77, 80, 84, 89, 95, 102, 110, 119, 129, 140, 152, 165, 15, 45, 58, 76, 79, 83, 88, 94, 101, 109, 118, 128, 139, 151, 164, 14, 178, 44, 57, 78, 82, 87, 93, 100, 108, 117, 127, 138, 150, 163, 13, 177, 190, 43, 56, 81, 86, 92, 99, 107, 116, 126, 137, 149, 162, 12, 176, 189, 201, 42, 55, 85, 91, 98, 106, 115, 125, 136, 148, 161, 11, 175, 188, 200, 211, 41, 54, 90, 97, 105, 114, 124, 135, 147, 160, 10, 174, 187, 199, 210, 220, 40, 53, 96, 104, 113, 123, 134, 146, 159, 9, 173, 186, 198, 209, 219, 228, 39, 52, 103, 112, 122, 133, 145, 158, 8, 172, 185, 197, 208, 218, 227, 235, 38, 51, 111, 121, 132, 144, 157, 7, 171, 184, 196, 207, 217, 226, 234, 241, 37, 50, 120, 131, 143, 156, 6, 170, 183, 195, 206, 216, 225, 233, 240, 246, 36, 49, 130, 142, 155, 5, 169, 182, 194, 205, 215, 224, 232, 239, 245, 250, 35, 48, 141, 154, 4, 168, 181, 193, 204, 214, 223, 231, 238, 244, 249, 253, 34, 47, 153, 3, 167, 180, 192, 203, 213, 222, 230, 237, 243, 248, 252, 255, 33, 46, 2, 166, 179, 191, 202, 212, 221, 229, 236, 242, 247, 251, 254, 256, 32, 1, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31";

结果是binary_ [i]与指定的数组不匹配,带有描述IndexOutOfRangeException was unhandled

1 个答案:

答案 0 :(得分:3)

如果您将input_plain[0]作为规则传递给您的函数,那么input_plain[0]256的条目将导致越界异常。

从代码中可以看出,规则被拆分为一个新的positionArray对象,其条目稍后被解析为整数并保存到循环的position变量中。然后使用位置变量来索引result_。由于未修改位置变量,因此它直接从规则字符串中使用256。由于result_字符数组只有256个条目,因此最后一个可索引条目将为255.因此,索引256将导致您看到的异常。

如果我不得不冒险猜测,我会说这段代码源自一种使用基于1的索引作为其数组的语言。似乎很可能因为我在input_plain[0]中没有看到数字0。也许只需将int position = int.Parse(positionArray[i]);更改为int position = int.Parse(positionArray[i]) - 1;即可解决您的问题。