Skip to content

Instantly share code, notes, and snippets.

@Dkowald
Last active October 13, 2023 17:36
Show Gist options
  • Select an option

  • Save Dkowald/9c4441359c948176b5be7797193e85d7 to your computer and use it in GitHub Desktop.

Select an option

Save Dkowald/9c4441359c948176b5be7797193e85d7 to your computer and use it in GitHub Desktop.
Dispose associated ICryptoTransform and algorithm along with CryptoStream
using System;
using System.IO;
using System.Security.Cryptography;
namespace kwd.gist
{
/// <summary>
/// Dispose associated <see cref="ICryptoTransform"/> and algorithm along with <see cref="CryptoStream"/>.
/// </summary>
/// <remarks>
/// Credit: Scott Chamberlain:
/// https://stackoverflow.com/questions/24188644/can-a-cryptostream-be-returned-and-still-have-everything-dispose-correctly
/// </remarks>
public class CryptoWrapper : CryptoStream
{
private ICryptoTransform? _transform;
private IDisposable? _algorithm;
private readonly Stream _stream;
public CryptoWrapper(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, IDisposable algorithm)
: base(stream, transform, mode)
{
_stream = stream;
_transform = transform;
_algorithm = algorithm;
}
public CryptoWrapper(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, bool leaveOpen, IDisposable algorithm)
: base(stream, transform, mode, leaveOpen)
{
_stream = stream;
_transform = transform;
_algorithm = algorithm;
}
protected override void Dispose(bool disposing)
{
try
{
base.Dispose(disposing);
}
catch (CryptographicException)
{
//The attempt to dispose cleans-up internal buffers. so no need to manually do it.
// but i do need to repair the missed inner-stream dispose (close).
//https://stackoverflow.com/questions/41230836/dispose-a-cryptostream-after-it-has-thrown-a-cryptographicexception
//https://stackoverflow.com/questions/37137536/c-sharp-encryption-system-security-cryptography-cryptographicexception-at-crypto
//https://stackoverflow.com/questions/45401733/disposing-cryptostream-vs-disposing-underlying-stream
if (disposing)
{ _stream.Dispose(); }
}
if (disposing)
{
_transform?.Dispose();
_transform = null;
_algorithm?.Dispose();
_algorithm = null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment