2

我必须编写一个对完整字节进行操作的 Vigenere 加密/解密函数(通过 tcp 加密和发送文件,然后在另一端解密)。我的加密功能似乎正在工作(或多或少,如果没有解密功能就无法真正测试它)。

这是加密函数的代码:

public static Byte[] encryptByteVigenere(Byte[] plaintext, string key) 
{

    Byte[] result= new Byte[plaintext.Length];

    key = key.Trim().ToUpper();

    int keyIndex = 0;
    int keylength = key.Length;

    for (int i = 0; i < plaintext.Length; i++)
    {
        keyIndex = keyIndex % keylength;
        int shift = (int)key[keyIndex] - 65;
        result[i] = (byte)(((int)plaintext[i] + shift) % 256);
        keyIndex++;
    }

    return result;
}

然而,解密函数,即使以几乎相同的方式编写,也会导致错误。“试图除以零。”

解密函数代码:

public static Byte[] decryptByteVigenere(Byte[] ciphertext, string key)
{
    Byte[] result = new Byte[ciphertext.Length];

    key = key.Trim().ToUpper();

    int keyIndex = 0;
    int keylength = key.Length;

    for (int i = 0; i < ciphertext.Length; i++)
    {             
        keyIndex = keyIndex % keylength;
        int shift = (int)key[keyIndex] - 65;
        result[i]= (byte)(((int)ciphertext[i] + 256 - shift) % 256);
        keyIndex++;               
    }

    return result;
}

错误点在 keyIndex = keyIndex % keylength; 但令我感到奇怪的是,第一个函数中的代码几乎相同,而且似乎没有造成任何麻烦。我正在接收的文件上对其进行测试,该文件在没有加密的情况下正确到达。有人可以帮我吗?

编辑:使用解密功能代码的方法/线程:

public void fileListenThread()
{         
    try
    {
        fileServer.Start();

        String receivedFileName = "test.dat";
        String key = (textKlucz.Text).ToUpper();

        while (true)
        {
            fileClient = fileServer.AcceptTcpClient();
            NetworkStream streamFileServer = fileClient.GetStream();
            int thisRead = 0;
            int blockSize = 1024;
            Byte[] dataByte = new Byte[blockSize];
            Byte[] dataByteDecrypted = new Byte[blockSize];

            FileStream fileStream = new FileStream(receivedFileName, FileMode.Create);
            while (true)
            {
                thisRead = streamFileServer.Read(dataByte, 0, blockSize);
                dataByteDecrypted = Program.decryptByteVigenere(dataByte, key);
                fileStream.Write(dataByteDecrypted, 0, thisRead);
                if (thisRead == 0)
                     break;
            }

            fileStream.Close();                 
        }
    }
    catch (SocketException e)
    {
        MessageBox.Show("SocketException: " + e, "Wystąpił wyjątek", MessageBoxButtons.OK, MessageBoxIcon.Error);               
    }
}
4

1 回答 1

0

好的,问题确实是发送/接收方法,而不是函数本身。我仍然不知道是什么导致了问题,但重写函数有帮助。感谢您的输入!

我把它留在这里,以防将来有人需要这样的功能......即使这是相当微不足道的事情。

干杯。

于 2012-11-15T13:52:29.737 回答