Decryption exception with Rijndael

I have a code that decrypts a password using Rijndael

public static string DecryptPassword(string encrypted) { using (MemoryStream ms = new MemoryStream()) using (RijndaelManaged rijndaelManaged = new RijndaelManaged()) using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor(mGlobalKey, mGlobalVector)) using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read)) { byte[] encryptedBytes = Convert.FromBase64String(encrypted); cs.Write(encryptedBytes, 0, encryptedBytes.Length); cs.FlushFinalBlock(); return Encoding.Unicode.GetString(ms.GetBuffer(), 0, (int)ms.Length); } } 

The problem is that removing the cryptostom causes an exception

 System.IndexOutOfRangeException : Index was outside the bounds of the array. at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.Stream.Dispose() 

I found some links to similar problems, but no solutions.

Is it safe to simply remove the Cryptostom Remover or will it cause the finalizer to explode later?

+4
source share
2 answers

You create steam in CryptoStreamMode.Read mode and try to write it.

+4
source

Although I could not find a good solution, I found these two solutions: A. Do not make the Encrypt / Decrypt static (C #) / shared (VB) function. (You must modify the code to create an instance of the RijndaelSimple object and then call the Encrypt / Decrypt functions. Possible reason: NOT sure, but maybe CryptoStream does not use the memory stream in a thread-safe way B. It seems that the exception is thrown ONLY when cipherText is an empty string. In 1.1, the function used to return an empty string when cipherText is an empty string. So just add this code to the first line in the Decrypt function: if (string.IsNullOrEmpty (cipherText)) return "";

I went with option B as // (It would be an effective soln since it only fails when cipherText = "// (Effective since it would still be a static function and it would not have to decrypt when cipherText =" ")

+1
source

Source: https://habr.com/ru/post/1340145/


All Articles