我正在为学校做一些项目。我正在与 TcpClient 和 TcpListener 进行服务器客户端通信。一开始我在服务器上创建 AES 密钥,然后使用 RSA 将其发送给客户端。我这里没有问题。但是,当我尝试在客户端加密字符串然后在服务器上对其进行加密时,我得到了一个异常。
- 填充无效且无法移除
服务器代码:
Byte[] bytes = new Byte[1024];
String data = null;
clientStream.Read(bytes, 0, bytes.Length); // preberemo iz streama
//Array.Clear(bytes, 0, bytes.Length);
// string temp = Encoding.UTF8.GetString(bytes11);
//temp = temp.Replace("\0", "");
//yte[] bytes = Encoding.UTF8.GetBytes(temp);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aes.CreateDecryptor(aes.Key,aes.IV), CryptoStreamMode.Write))
{
//StreamWriter swEncrypt = new StreamWriter(csEncrypt);
csEncrypt.Write(bytes, 0, bytes.Length);
}
byte[] encrypted = msEncrypt.ToArray();
string enc = Encoding.UTF8.GetString(encrypted, 0, encrypted.Length);
}
客户端代码:
byte[] messg = Encoding.UTF8.GetBytes(messig);
// dobimo client stream
string enc = null;
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
{
csEncrypt.Write(messg,0,messg.Length);
}
byte[] encrypted = msEncrypt.ToArray();
enc = Encoding.UTF8.GetString(encrypted, 0, encrypted.Length);
}
byte[] data = new byte[1024];
data = Encoding.UTF8.GetBytes(enc);
//CryptoStream CryptStream = new CryptoStream(stream,aes.CreateEncryptor(aes.Key, aes.IV),CryptoStreamMode.Write);
stream.Write(data, 0, data.Length); // pošljem sporočilo
尝试使用 msEncrypt.ToArray(); 时服务器出现异常
但是,如果我动态地分配 Byte[],或者我删除了所有空值,我会得到一个异常,说“输入数据不是一个完整的块”。