Why does a bad password cause “Padding is invalid and cannot be removed”?

前端 未结 9 1580
醉酒成梦
醉酒成梦 2020-11-29 07:24

I needed some simple string encryption, so I wrote the following code (with a great deal of \"inspiration\" from here):

    // create and initialize a crypto         


        
9条回答
  •  醉酒成梦
    2020-11-29 07:58

    I experienced a similar "Padding is invalid and cannot be removed." exception, but in my case the key IV and padding were correct.

    It turned out that flushing the crypto stream is all that was missing.

    Like this:

                MemoryStream msr3 = new MemoryStream();
                CryptoStream encStream = new CryptoStream(msr3, RijndaelAlg.CreateEncryptor(), CryptoStreamMode.Write);
                encStream.Write(bar2, 0, bar2.Length);
                // unless we flush the stream we would get "Padding is invalid and cannot be removed." exception when decoding
                encStream.FlushFinalBlock();
                byte[] bar3 = msr3.ToArray();
    

提交回复
热议问题