首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#希尔-密码最后3个字符错误,其余正确

C#希尔-密码最后3个字符错误,其余正确
EN

Stack Overflow用户
提问于 2018-07-12 16:56:46
回答 0查看 449关注 0票数 1

我目前正在尝试在C#中实现Hill-Cipher,并且遇到了一些我不能理解的奇怪的事情。我的代码看起来像这样:

代码语言:javascript
复制
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.frcryptool.org。我每次都发现最后三个字符总是不同的,但其余的是匹配的。这就是我的意思:Result of my coderesult of dcode.frresult of cryptool.org正如你所看到的,这两个站点提供了相同的结果,只是后三个字符与我的不同。

上面的代码来自一个C#类,它是Visual Studio项目的一部分,你可以找到源代码here

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51301286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档