自定义加密

本文关键字:加密 自定义 | 更新日期: 2023-09-27 18:04:17

我正在制作一个自定义加密/解密软件。我已经写好了代码:

    public int CountCharInStringAccordingToArray(string Text)
    {
        int Count = 0;
        foreach (char x in Text)
        {
            Count++;
        }
        return Count - 1;
    }
    public int CountCharInString(string Text)
    {
        int Count = 0;
        foreach (char x in Text)
        {
            Count++;
        }
        return Count;
    }
    public string Encrypt(string Key, string PlainText)
    {
        int[] TempKey = new int[CountCharInString(Key)];
        int[] TempText = new int[CountCharInString(PlainText)];
        int[] EncryptedInt = new int[CountCharInString(PlainText)];
        char[] EncryptedChar = new char[CountCharInString(PlainText)];
        for (int i = 0; i < CountCharInStringAccordingToArray(Key); i++)
        {
            TempKey[i] = (int)Key[i];
        }
        for (int i = 0; i < CountCharInStringAccordingToArray(PlainText); i++)
        {
            TempText[i] = (int)PlainText[i];
        }
        int Index = 0;
        for (int i = 0; i < CountCharInStringAccordingToArray(PlainText); i++)
        {
            if (Index == CountCharInStringAccordingToArray(Key))
            {
                Index = 0;
            }
            EncryptedInt[i] = TempKey[Index] + TempText[i];
            Index++;
            EncryptedChar[i] = (char)EncryptedInt[i];
        }
        return new string(EncryptedChar);
    }
    public string Decrypt(string Key, string EncryptedText)
    {
        int[] TempKey = new int[CountCharInString(Key)];
        int[] TempText = new int[CountCharInString(EncryptedText)];
        int[] DecryptedInt = new int[CountCharInString(EncryptedText)];
        char[] DecryptedChar = new char[CountCharInString(EncryptedText)];
        for (int i = 0; i < CountCharInStringAccordingToArray(Key); i++)
        {
            TempKey[i] = (int)Key[i];
        }
        for (int i = 0; i < CountCharInStringAccordingToArray(EncryptedText); i++)
        {
            TempText[i] = (int)EncryptedText[i];
        }
        int Index = 0;
        for (int i = 0; i < CountCharInStringAccordingToArray(EncryptedText); i++)
        {
            if (Index == CountCharInStringAccordingToArray(Key))
            {
                Index = 0;
            }
            DecryptedInt[i] = TempText[i] - TempKey[Index];
            Index++;
            DecryptedChar[i] = (char)DecryptedInt[i];
        }
        return new string(DecryptedChar);
    }

但是我的问题是当我加密:

Key = abc123

明文=大家好,你们好吗?

加密结果:§没有

当我解密时:

Key = abc123

EncryptedText =§ÑÕ

解密结果:

当我解密加密文本时,我得到的结果与"大家好,你们好吗?"完全不同。

有人能帮忙吗?

自定义加密

虽然其他人已经说了很多,但代码中的实际问题是在加密和解密函数中使用属性"Text"。在你的函数头中,输入参数是"明文"answers"EncryptedText",但在你的函数体中,你试图使用"文本"来引用它们。Text属性属于你的程序的主窗口——你的Encrypt和Decrypt函数都在该文本上执行它们的操作,而不管你实际输入的文本是什么。

作为c#的一般规则,尽量不要让你的局部变量以大写字母开头。以大写字母开头的名称通常保留给属性和方法。正如您从代码中的错误中看到的那样,您引用了一个与您期望的变量完全不同的属性。采用驼峰大小写这样的命名方案可以避免这类无意的引用,并允许调试器在您犯了这类错误时告诉您。