【发布时间】:2012-11-02 09:06:56
【问题描述】:
我必须编写一个对完整字节进行操作的 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 % 密钥长度; 但令我感到奇怪的是,第一个函数中的代码几乎相同,而且似乎没有造成任何麻烦。我正在接收的文件上对其进行测试,该文件在没有加密的情况下正确到达。谁能帮我解决这个问题?
编辑: 正在使用解密函数代码的方法/线程:
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);
}
}
【问题讨论】:
-
decryptByteVigenere中
klucz和szyfr的定义在哪里 -
已修复。我正在翻译变量,一定错过了这些,抱歉!
-
这似乎不太可能引发 div-by-zero 异常,除非
key.Length==0。请发布显示问题的完整代码。 -
不,它不是0。我使用相同的密钥来加密和解密(它是同一个窗口应用程序)。然而它仍然停在 keyIndex = keyIndex % keylength; 行。整个代码几乎就是整个 Windows 应用程序,包括表单。
-
在这一行设置断点,观察
keylength和key。