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