From d4fc31da8d2af75becb076d3784313ff6a02ad93 Mon Sep 17 00:00:00 2001 From: Avril Date: Sun, 1 Dec 2019 16:17:25 +0000 Subject: [PATCH] fixed not disposing RSA keys --- libstenet/EncryptedNetwork.cs | 21 ++++++++++++++++++--- libstenet/Internal.cs | 12 ++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/libstenet/EncryptedNetwork.cs b/libstenet/EncryptedNetwork.cs index 303efdb..cfe72b2 100644 --- a/libstenet/EncryptedNetwork.cs +++ b/libstenet/EncryptedNetwork.cs @@ -264,7 +264,7 @@ namespace EncryptedNetwork ~EncryptedWriteBlock() { Dispose(false); aes = null; } } - private readonly RSACryptoServiceProvider you; + private RSACryptoServiceProvider you; private RSACryptoServiceProvider them; /// @@ -305,7 +305,7 @@ namespace EncryptedNetwork /// Initialise a new from a /// /// The Stream to set backing for. - public EncryptedNetworkStream(NetworkStream stream) : this(stream, new RSACryptoServiceProvider()) { } + public EncryptedNetworkStream(NetworkStream stream) : this(stream, new RSACryptoServiceProvider()) { KeepPrivateCSPAlive = false; } /// /// Initialise a new from a /// @@ -318,7 +318,7 @@ namespace EncryptedNetwork /// /// The Socket to set backing for. (NOTE: Closes the socket on dispose) public EncryptedNetworkStream(Socket sock) - : this(sock, new RSACryptoServiceProvider()) { } + : this(sock, new RSACryptoServiceProvider()) { KeepPrivateCSPAlive = false; } /// /// Exchange the RSA public keys asynchronously. @@ -360,10 +360,25 @@ namespace EncryptedNetwork public void Exchange() => ExchangeAsync().Sync(); + /// + /// Keep alive after disposing? + /// + public bool KeepPrivateCSPAlive { get; set; } = true; protected override void Dispose(bool disposing) { base.Dispose(disposing); + + if(disposing) + { + if (!KeepPrivateCSPAlive) + you.Dispose(); + them?.Dispose(); + } + + you = null; + them = null; } + ~EncryptedNetworkStream() => Dispose(false); /// /// Read unencrypted data from the backing stream. diff --git a/libstenet/Internal.cs b/libstenet/Internal.cs index 61b7bd9..e476d4a 100644 --- a/libstenet/Internal.cs +++ b/libstenet/Internal.cs @@ -30,12 +30,24 @@ namespace EncryptedNetwork backing = s; } + protected ObjectDisposedException ThrowIfDisposed() + { + if (Disposed) + throw new ObjectDisposedException(GetType().Name + " object has been disposed."); + else return null; + } + + protected bool Disposed { get; private set; } = false; protected override void Dispose(bool disposing) { + ThrowIfDisposed(); + + Disposed = true; if (disposing) { if (!KeepBackingStreamAlive) backing.Dispose(); } + backing = null; } #region Stream Overrides