【发布时间】:2017-07-26 16:56:14
【问题描述】:
我看到很多人在这里遇到这个异常的问题,但我根本不明白解决方案。 简短回顾: 我的程序是 C# 中的 GUI 程序,假设在本地网络中的两台计算机上运行并始终同步,因此,您会从另一台计算机获得某种共享空间与您的朋友一起工作。 我的密码学是在一个单例实例中,它负责我的程序的通信。以下是加密和解密数据的函数,它们以文本或字节数组的形式接收数据,并将其作为字节数组或文本返回(取决于解密/加密哪一个):
public static byte[] Encrypt(string text)
{
desObj = Rijndael.Create();
byte[] cipherBytes;
byte[] plainBytes;
byte[] plainKey;
plainBytes = Encoding.ASCII.GetBytes(text);
plainKey= Encoding.ASCII.GetBytes("0123456789abcdef");//Change the key.
desObj.Key = plainKey;
desObj.Mode = CipherMode.CFB;
desObj.Padding = PaddingMode.PKCS7;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, desObj.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(plainBytes, 0, plainBytes.Length);
cs.Close();
cipherBytes = ms.ToArray();
ms.Close();
return cipherBytes;
}
public static string Decrypt(byte[] x)
{
byte[] plainBytes;
byte[] plainKey;
desObj = Rijndael.Create();
plainKey = Encoding.ASCII.GetBytes("0123456789abcdef");//Change the key.
desObj.Key = plainKey;
desObj.Mode = CipherMode.CFB;
desObj.Padding = PaddingMode.PKCS7;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, desObj.CreateDecryptor(), CryptoStreamMode.Read);
cs.Read(x, 0, x.Length);
plainBytes = ms.ToArray();
cs.Close();
ms.Close();
return Encoding.ASCII.GetString(plainBytes);
}
public static void RecievingMessage()
{
try
{
if (srvr != null && openForms != null)//openForms is a list of all the current open forms.
{
byte[] data = new byte[1024];
int i = 0;
string[] message;
if (srvr != null)
while (true)
{
Thread.Sleep(20);
int bytesRec = srvr.Receive(data);
message = Decrypt(data).Split(' ');
for (i = 0; i < openForms.Count; i++)
{
if (message[0].Equals(openForms[i].Name))
{
openForms[i].Recieve(message);
}
}
}
}
}
....//Catch clauses.
}
public static void SendMessage(string sender, string message)
{
if (srvr != null)
{
try
{
srvr.Send(Encrypt(sender + " " + message + " "));
}
...//Catch clauses.
}
}
当我运行这个程序时控制台上显示“Padding is invalid and cannot be removed”,我知道加密成功(当它通过服务器时我看到它被加密)但是当我尝试解密它时写入异常。
【问题讨论】:
-
当我运行这个程序时,控制台显示“Padding is invalid and cannot be removed”,我知道加密是成功的(当它通过服务器时我看到它被加密了)但是当我尝试解密它写入异常。 @dbugger
-
这段代码有很多错误 - 例如,您需要 Dispose Disposable。从密码中获取密钥的方式非常弱。还有一个你永远不会调用的 FlushFinalBlock(),最好在关闭它之后从 MemoryStream 中获取数组。
-
所以去寻找一个好的工作示例。
标签: c# exception encryption padding