gpt4 book ai didi

c# - Byte Vigenere Cipher,解密错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:53 24 4
gpt4 key购买 nike

我必须编写一个对完整字节进行操作的 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);
}
}

最佳答案

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

我把它留在这里,以防将来有人需要这样的功能……尽管这是一件微不足道的事情。

干杯。

关于c# - Byte Vigenere Cipher,解密错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13369178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com