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

前端 未结 9 1585
醉酒成梦
醉酒成梦 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:34

    If you've ruled out key-mismatch, then besides FlushFinalBlock() (see Yaniv's answer), calling Close() on the CryptoStream will also suffice.

    If you are cleaning up resources strictly with using blocks, be sure to nest the block for the CryptoStream itself:

    using (MemoryStream ms = new MemoryStream())
    using (var enc = RijndaelAlg.CreateEncryptor())
    {
      using (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))
      {
        encStream.Write(bar2, 0, bar2.Length);
      } // implicit close
      byte[] encArray = ms.ToArray();
    }
    

    I've been bitten by this (or similar):

    using (MemoryStream ms = new MemoryStream())
    using (var enc = RijndaelAlg.CreateEncryptor())
    using (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))
    {
      encStream.Write(bar2, 0, bar2.Length);
      byte[] encArray = ms.ToArray();
    } // implicit close -- too late!
    

提交回复
热议问题