程序B发消息:
string msg = "Hello from B!";
byte[] msgbuf = Encoding.Unicode.GetBytes(msg);
byte[] encbuf = EncryptData(msgbuf,rm.Key,rm.IV);
NetStream.Write(encbuf,0,encbuf.Length);
程序A收消息:
byte[] mbuf = new byte[256];
NetStream.Read(mbuf, 0, 256);
byte[] decbuf = DecryptData(mbuf,key,iv);每次都在DecryptData这里出错,异常如下:
System.Security.Cryptography.CryptographicException: PKCS7 填充无效,无法被移除

   at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(
Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
   at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
   at System.Security.Cryptography.CryptoStream.Close()
   at Security.Class1.DecryptData(Byte[] inBuf, Byte[] rijnKey, Byte[] rijnIV) i
n d:\myprojects\securea\securea.cs:line 136
   at Security.Class1.Main(String[] args) in d:\myprojects\securea\securea.cs:li
ne 56
请大侠帮忙,非常感谢!另外,如果我用TCP一直保持连接,采用StreamWriter和StreamReader来加密和解密数据,总是必须把StreamWriter关闭之后,StreamReader才能收到消息,这样很烦人的。请问高人有什么解决办法?

解决方案 »

  1.   

    改成这样也不行:
    //Creates the default implementation, which is RijndaelManaged.     
    SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();     
    CryptoStream decStream = new CryptoStream(inStream, 
    rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Read);//Read from the input, then encrypt and write to the output.
    int len = decStream.Read(bin, 0, inBuf.Length);
    outStream.Write(bin, 0, len);异常为:
    System.Security.Cryptography.CryptographicException: PKCS7 填充无效,无法被移除

       at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(
    Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
       at System.Security.Cryptography.CryptoStream.Read(Byte[] buffer, Int32 offset
    , Int32 count)
       at Security.Class1.DecryptData(Byte[] inBuf, Byte[] rijnKey, Byte[] rijnIV) i
    n d:\myprojects\securea\securea.cs:line 132
       at Security.Class1.Main(String[] args) in d:\myprojects\securea\securea.cs:li
    ne 56
      

  2.   

    isolate errors first pls. now the problem is decrytion or write & read?
      

  3.   

    athossmth大侠,你说的是decryption时,用write还是read吧?
    好像两种我都试过了。
      

  4.   

    改一下,写成类似于win2000的对称加密。
      

  5.   

    to hivak47(比尔):
    我这就是用的对称加密啊。