我目前正在尝试在C#中实现Hill-Cipher,并且遇到了一些我不能理解的奇怪的事情。我的代码看起来像这样:
public string Encrypt(string plaintext)
{
plaintext = plaintext.ToLower();
plaintext = plaintext.Replace(" ", "");
string ciphertext = null;
int[,] keyMatrix = new int[,] { { 13, 7, 16 }, { 19, 4, 8 }, { 4, 22, 7 } }; //Sample Matrix, should later be given as "key"
int[] valueOfCharMatrix = new int[plaintext.Length + (plaintext.Length % 3)], cipherValueOfCharMatrix = new int[plaintext.Length + (plaintext.Length % 3)];
//Convert full plaintext to it's INT value
for (int i = 0; i < plaintext.Length; i++)
{
valueOfCharMatrix[i] = (byte)(plaintext[i] - 'a');
}
for (int i = 0; i < valueOfCharMatrix.Length - (valueOfCharMatrix.Length % 3); i += 3)
{
for (int j = 0; j < 3; j++)
{
//Matrix multiplication, keyMatrix * valueOfCharMatrix mod 26
cipherValueOfCharMatrix[i + j] = (valueOfCharMatrix[i] * keyMatrix[j, 0] +
valueOfCharMatrix[i + 1] * keyMatrix[j, 1] +
valueOfCharMatrix[i + 2] * keyMatrix[j, 2]) % 26; //i % 3 works
}
}
//Convert cipher INTs to chars
for (int i = 0; i < cipherValueOfCharMatrix.Length; i++)
{
ciphertext += (char)(cipherValueOfCharMatrix[i] + 'a');
}
return ciphertext;
}如果我运行这个程序,加密一些东西,然后对照以下两个站点的结果进行检查:dcode.fr和cryptool.org。我每次都发现最后三个字符总是不同的,但其余的是匹配的。这就是我的意思:Result of my code,result of dcode.fr,result of cryptool.org正如你所看到的,这两个站点提供了相同的结果,只是后三个字符与我的不同。
上面的代码来自一个C#类,它是Visual Studio项目的一部分,你可以找到源代码here。
https://stackoverflow.com/questions/51301286
复制相似问题