As stated elsewhere, objects that implement IDisposable do not immediately collect garbage. If you do not call Dispose on a disposable object, either explicitly or wrapping it in use, this object will take longer to collect garbage.
If you use a try, you should consider declaring such variables outside of try and implement deletion in the finally block. In particular, with AesCryptoServiceProvider, where you want to make sure that the Clear () method is launched even if an error occurs, since using it will not do this for you.
public static string Decrypt(string cipherText) { string decryptedMessage = null; AesCryptoServiceProvider Aes = null; ICryptoTransform cTransform = null; try { //Decrypt: byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] toDecryptArray = Convert.FromBase64String(cipherText); AesCryptoServiceProvider Aes = new AesCryptoServiceProvider(); Aes.Key = keyArray; Aes.Mode = CipherMode.CBC; Aes.Padding = PaddingMode.PKCS7; Aes.IV = IV; ICryptoTransform cTransform = Aes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); decryptedMessage = UTF8Encoding.UTF8.GetString(resultArray, 0, resultArray.Length); } catch (Exception ex) { decryptedMessage = "FAILED:*" + cipherText + "*" + ex.Message; } finally { if (cTransform != null) { cTransform.Dispose(); } if (Aes != null) { Aes.Clear(); Aes.Dispose(); } } return decryptedMessage; }
You should also consider allowing an exception by excluding the catch block and saving it, and handling it outside of this method.
You can also return bool for success / failure and pass your decrypted string using out. Thus, you will not confuse your mistakes with the contents of your message:
public bool string Decrypt(string cipherText, out string decryptedMessage) { bool succeeded = false; decryptedMessage = null; AesCryptoServiceProvider Aes = null; ICryptoTransform cTransform = null; try { //Decrypt: byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] toDecryptArray = Convert.FromBase64String(cipherText); AesCryptoServiceProvider Aes = new AesCryptoServiceProvider(); Aes.Key = keyArray; Aes.Mode = CipherMode.CBC; Aes.Padding = PaddingMode.PKCS7; Aes.IV = IV; ICryptoTransform cTransform = Aes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); decryptedMessage = UTF8Encoding.UTF8.GetString(resultArray, 0, resultArray.Length); succeeded = true; } catch (Exception ex) { decryptedMessage = "FAILED:*" + cipherText + "*" + ex.Message; } finally { if (cTransform != null) { cTransForm.Dispose(); } if (Aes != null) { Aes.Clear(); Aes.Dispose(); } } return succeeded; }
source share