summary refs log tree commit diff
diff options
context:
space:
mode:
authorPeter Dettman <peter.dettman@bouncycastle.org>2022-11-09 01:13:27 +0700
committerPeter Dettman <peter.dettman@bouncycastle.org>2022-11-09 01:13:27 +0700
commita8a17fd70fc8df3ca7402323ad5c4f36b25cb806 (patch)
tree9b276b62885505abbb899d17744b65b912072140
parentPrimes improvements (diff)
downloadBouncyCastle.NET-ed25519-a8a17fd70fc8df3ca7402323ad5c4f36b25cb806.tar.xz
Dispose cleanup
- IDisposable for PemReader, PemWriter, IStreamGenerator
-rw-r--r--crypto/src/bcpg/ArmoredInputStream.cs2
-rw-r--r--crypto/src/bcpg/BcpgInputStream.cs2
-rw-r--r--crypto/src/bcpg/BcpgOutputStream.cs2
-rw-r--r--crypto/src/cmp/ProtectedPkiMessage.cs7
-rw-r--r--crypto/src/cms/CMSAuthenticatedDataGenerator.cs9
-rw-r--r--crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs2
-rw-r--r--crypto/src/cms/CMSCompressedData.cs2
-rw-r--r--crypto/src/cms/CMSCompressedDataGenerator.cs8
-rw-r--r--crypto/src/cms/CMSCompressedDataStreamGenerator.cs2
-rw-r--r--crypto/src/cms/CMSContentInfoParser.cs2
-rw-r--r--crypto/src/cms/CMSEnvelopedDataGenerator.cs18
-rw-r--r--crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs2
-rw-r--r--crypto/src/cms/CMSProcessableFile.cs7
-rw-r--r--crypto/src/cms/CMSProcessableInputStream.cs2
-rw-r--r--crypto/src/cms/CMSSignedDataParser.cs4
-rw-r--r--crypto/src/cms/CMSSignedDataStreamGenerator.cs13
-rw-r--r--crypto/src/cms/CMSTypedStream.cs2
-rw-r--r--crypto/src/crmf/EncryptedValueBuilder.cs8
-rw-r--r--crypto/src/crmf/ProofOfPossessionSigningKeyBuilder.cs10
-rw-r--r--crypto/src/crypto/io/CipherStream.cs2
-rw-r--r--crypto/src/crypto/io/DigestStream.cs2
-rw-r--r--crypto/src/crypto/io/MacStream.cs2
-rw-r--r--crypto/src/crypto/io/SignerStream.cs2
-rw-r--r--crypto/src/crypto/parameters/SkeinParameters.cs17
-rw-r--r--crypto/src/openpgp/IStreamGenerator.cs4
-rw-r--r--crypto/src/openpgp/PgpCompressedDataGenerator.cs45
-rw-r--r--crypto/src/openpgp/PgpEncryptedDataGenerator.cs83
-rw-r--r--crypto/src/openpgp/PgpLiteralDataGenerator.cs34
-rw-r--r--crypto/src/openpgp/PgpUtilities.cs4
-rw-r--r--crypto/src/openpgp/WrappedGeneratorStream.cs11
-rw-r--r--crypto/src/openssl/PEMReader.cs2
-rw-r--r--crypto/src/openssl/PEMWriter.cs4
-rw-r--r--crypto/src/pkcs/Pkcs10CertificationRequest.cs8
-rw-r--r--crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs8
-rw-r--r--crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs10
-rw-r--r--crypto/src/pkix/PkixCertPath.cs12
-rw-r--r--crypto/src/tls/CertificateUrl.cs2
-rw-r--r--crypto/src/tls/HandshakeMessageOutput.cs2
-rw-r--r--crypto/src/tls/RecordStream.cs4
-rw-r--r--crypto/src/tls/TlsUtilities.cs2
-rw-r--r--crypto/src/tsp/TimeStampTokenGenerator.cs12
-rw-r--r--crypto/src/util/Platform.cs5
-rw-r--r--crypto/src/util/bzip2/CBZip2InputStream.cs2
-rw-r--r--crypto/src/util/bzip2/CBZip2OutputStream.cs2
-rw-r--r--crypto/src/util/io/TeeInputStream.cs4
-rw-r--r--crypto/src/util/io/TeeOutputStream.cs4
-rw-r--r--crypto/src/util/io/pem/PemReader.cs29
-rw-r--r--crypto/src/util/io/pem/PemWriter.cs32
-rw-r--r--crypto/src/util/zlib/ZInputStream.cs2
-rw-r--r--crypto/src/util/zlib/ZOutputStream.cs2
-rw-r--r--crypto/src/x509/X509Certificate.cs12
-rw-r--r--crypto/src/x509/X509Crl.cs14
-rw-r--r--crypto/src/x509/X509V2AttributeCertificate.cs7
-rw-r--r--crypto/test/src/crypto/io/test/PemReaderTest.cs51
-rw-r--r--crypto/test/src/openpgp/test/DSA2Test.cs2
-rw-r--r--crypto/test/src/openpgp/test/PGPCompressionTest.cs8
-rw-r--r--crypto/test/src/openpgp/test/PGPDSAElGamalTest.cs4
-rw-r--r--crypto/test/src/openpgp/test/PGPDSATest.cs8
-rw-r--r--crypto/test/src/openpgp/test/PGPPBETest.cs10
-rw-r--r--crypto/test/src/openpgp/test/PGPPacketTest.cs2
-rw-r--r--crypto/test/src/openpgp/test/PGPRSATest.cs2
-rw-r--r--crypto/test/src/openpgp/test/PGPSignatureTest.cs8
-rw-r--r--crypto/test/src/openssl/test/AllTests.cs45
-rw-r--r--crypto/test/src/openssl/test/ReaderTest.cs172
-rw-r--r--crypto/test/src/openssl/test/WriterTest.cs62
-rw-r--r--crypto/test/src/test/rsa3/RSA3CertTest.cs9
-rw-r--r--crypto/test/src/tls/test/TlsTestUtilities.cs9
-rw-r--r--crypto/test/src/util/io/pem/test/AllTests.cs23
68 files changed, 493 insertions, 413 deletions
diff --git a/crypto/src/bcpg/ArmoredInputStream.cs b/crypto/src/bcpg/ArmoredInputStream.cs
index 4fbb8baae..ab9a303dd 100644
--- a/crypto/src/bcpg/ArmoredInputStream.cs
+++ b/crypto/src/bcpg/ArmoredInputStream.cs
@@ -507,7 +507,7 @@ namespace Org.BouncyCastle.Bcpg
         {
             if (disposing)
             {
-                Platform.Dispose(input);
+                input.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/bcpg/BcpgInputStream.cs b/crypto/src/bcpg/BcpgInputStream.cs
index 3b6f61bbc..44d2f9c02 100644
--- a/crypto/src/bcpg/BcpgInputStream.cs
+++ b/crypto/src/bcpg/BcpgInputStream.cs
@@ -270,7 +270,7 @@ namespace Org.BouncyCastle.Bcpg
         {
             if (disposing)
             {
-                Platform.Dispose(m_in);
+                m_in.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/bcpg/BcpgOutputStream.cs b/crypto/src/bcpg/BcpgOutputStream.cs
index 690686d88..c6a9b8657 100644
--- a/crypto/src/bcpg/BcpgOutputStream.cs
+++ b/crypto/src/bcpg/BcpgOutputStream.cs
@@ -434,7 +434,7 @@ namespace Org.BouncyCastle.Bcpg
             {
 			    this.Finish();
 			    outStr.Flush();
-                Platform.Dispose(outStr);
+                outStr.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/cmp/ProtectedPkiMessage.cs b/crypto/src/cmp/ProtectedPkiMessage.cs
index f99672cc7..6304b5200 100644
--- a/crypto/src/cmp/ProtectedPkiMessage.cs
+++ b/crypto/src/cmp/ProtectedPkiMessage.cs
@@ -126,9 +126,10 @@ namespace Org.BouncyCastle.Cmp
             avec.Add(m_pkiMessage.Body);
             byte[] enc = new DerSequence(avec).GetDerEncoded();
 
-            streamCalculator.Stream.Write(enc, 0, enc.Length);
-            streamCalculator.Stream.Flush();
-            Platform.Dispose(streamCalculator.Stream);
+            using (var stream = streamCalculator.Stream)
+            {
+                stream.Write(enc, 0, enc.Length);
+            }
 
             return streamCalculator.GetResult();
         }
diff --git a/crypto/src/cms/CMSAuthenticatedDataGenerator.cs b/crypto/src/cms/CMSAuthenticatedDataGenerator.cs
index f6827157c..95e710c9b 100644
--- a/crypto/src/cms/CMSAuthenticatedDataGenerator.cs
+++ b/crypto/src/cms/CMSAuthenticatedDataGenerator.cs
@@ -71,11 +71,10 @@ namespace Org.BouncyCastle.Cms
 				mac.Init(encKey);
 
 				var bOut = new MemoryStream();
-				Stream mOut = new TeeOutputStream(bOut, new MacSink(mac));
-
-				content.Write(mOut);
-
-                Platform.Dispose(mOut);
+				using (var mOut = new TeeOutputStream(bOut, new MacSink(mac)))
+				{
+					content.Write(mOut);
+				}
 
                 encContent = new BerOctetString(bOut.ToArray());
 
diff --git a/crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs b/crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs
index 6348431a2..fd2c743bb 100644
--- a/crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs
+++ b/crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs
@@ -253,7 +253,7 @@ namespace Org.BouncyCastle.Cms
             {
                 if (disposing)
                 {
-                    Platform.Dispose(macStream);
+                    macStream.Dispose();
 
                     // TODO Parent context(s) should really be be closed explicitly
 
diff --git a/crypto/src/cms/CMSCompressedData.cs b/crypto/src/cms/CMSCompressedData.cs
index 5f8165005..4bfac3a93 100644
--- a/crypto/src/cms/CMSCompressedData.cs
+++ b/crypto/src/cms/CMSCompressedData.cs
@@ -56,7 +56,7 @@ namespace Org.BouncyCastle.Cms
 			}
 			finally
 			{
-                Platform.Dispose(zIn);
+                zIn.Dispose();
 			}
         }
 
diff --git a/crypto/src/cms/CMSCompressedDataGenerator.cs b/crypto/src/cms/CMSCompressedDataGenerator.cs
index 70515e8d3..e60effa61 100644
--- a/crypto/src/cms/CMSCompressedDataGenerator.cs
+++ b/crypto/src/cms/CMSCompressedDataGenerator.cs
@@ -42,11 +42,11 @@ namespace Org.BouncyCastle.Cms
             try
             {
                 MemoryStream bOut = new MemoryStream();
-                Stream zOut = Utilities.IO.Compression.ZLib.CompressOutput(bOut, -1);
 
-				content.Write(zOut);
-
-                Platform.Dispose(zOut);
+                using (var zOut = Utilities.IO.Compression.ZLib.CompressOutput(bOut, -1))
+                {
+                    content.Write(zOut);
+                }
 
                 comAlgId = new AlgorithmIdentifier(CmsObjectIdentifiers.ZlibCompress);
 				comOcts = new BerOctetString(bOut.ToArray());
diff --git a/crypto/src/cms/CMSCompressedDataStreamGenerator.cs b/crypto/src/cms/CMSCompressedDataStreamGenerator.cs
index 3669c0b3a..64a978c6d 100644
--- a/crypto/src/cms/CMSCompressedDataStreamGenerator.cs
+++ b/crypto/src/cms/CMSCompressedDataStreamGenerator.cs
@@ -135,7 +135,7 @@ namespace Org.BouncyCastle.Cms
             {
                 if (disposing)
                 {
-                    Platform.Dispose(_out);
+                    _out.Dispose();
 
                     // TODO Parent context(s) should really be be closed explicitly
 
diff --git a/crypto/src/cms/CMSContentInfoParser.cs b/crypto/src/cms/CMSContentInfoParser.cs
index a7b43f295..c3bc9e736 100644
--- a/crypto/src/cms/CMSContentInfoParser.cs
+++ b/crypto/src/cms/CMSContentInfoParser.cs
@@ -42,7 +42,7 @@ namespace Org.BouncyCastle.Cms
 		*/
 		public void Close()
 		{
-            Platform.Dispose(this.data);
+            data.Dispose();
 		}
 	}
 }
diff --git a/crypto/src/cms/CMSEnvelopedDataGenerator.cs b/crypto/src/cms/CMSEnvelopedDataGenerator.cs
index 1b618b331..d2cd18885 100644
--- a/crypto/src/cms/CMSEnvelopedDataGenerator.cs
+++ b/crypto/src/cms/CMSEnvelopedDataGenerator.cs
@@ -67,11 +67,10 @@ namespace Org.BouncyCastle.Cms
 				cipher.Init(true, new ParametersWithRandom(cipherParameters, m_random));
 
 				MemoryStream bOut = new MemoryStream();
-				CipherStream cOut = new CipherStream(bOut, null, cipher);
-
-				content.Write(cOut);
-
-                Platform.Dispose(cOut);
+                using (var cOut = new CipherStream(bOut, null, cipher))
+                {
+                    content.Write(cOut);
+                }
 
                 encContent = new BerOctetString(bOut.ToArray());
 			}
@@ -159,9 +158,12 @@ namespace Org.BouncyCastle.Cms
                 encKey = (KeyParameter) cipherBuilder.Key;
 
                 MemoryStream collector = new MemoryStream();
-                Stream bOut = cipherBuilder.BuildCipher(collector).Stream;            
-                content.Write(bOut);  
-                Platform.Dispose(bOut);                            
+                var cipher = cipherBuilder.BuildCipher(collector);
+                using (var bOut = cipher.Stream)
+                {
+                    content.Write(bOut);
+                }
+
                 encContent = new BerOctetString(collector.ToArray());
             }
             catch (SecurityUtilityException e)
diff --git a/crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs b/crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs
index ad356a208..aafebee44 100644
--- a/crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs
+++ b/crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs
@@ -256,7 +256,7 @@ namespace Org.BouncyCastle.Cms
             {
                 if (disposing)
  				{
-                    Platform.Dispose(_out);
+                    _out.Dispose();
 
                     // TODO Parent context(s) should really be closed explicitly
 
diff --git a/crypto/src/cms/CMSProcessableFile.cs b/crypto/src/cms/CMSProcessableFile.cs
index 255c8432f..0344759cc 100644
--- a/crypto/src/cms/CMSProcessableFile.cs
+++ b/crypto/src/cms/CMSProcessableFile.cs
@@ -34,9 +34,10 @@ namespace Org.BouncyCastle.Cms
 
         public virtual void Write(Stream zOut)
 		{
-			Stream inStr = _file.OpenRead();
-            Streams.PipeAll(inStr, zOut, _bufSize);
-            Platform.Dispose(inStr);
+			using (var inStr = _file.OpenRead())
+			{
+                Streams.PipeAll(inStr, zOut, _bufSize);
+            }
 		}
 	}
 }
diff --git a/crypto/src/cms/CMSProcessableInputStream.cs b/crypto/src/cms/CMSProcessableInputStream.cs
index 8fb3adbff..1a80ccfd6 100644
--- a/crypto/src/cms/CMSProcessableInputStream.cs
+++ b/crypto/src/cms/CMSProcessableInputStream.cs
@@ -30,7 +30,7 @@ namespace Org.BouncyCastle.Cms
 			CheckSingleUsage();
 
 			Streams.PipeAll(input, output);
-            Platform.Dispose(input);
+            input.Dispose();
 		}
 
         protected virtual void CheckSingleUsage()
diff --git a/crypto/src/cms/CMSSignedDataParser.cs b/crypto/src/cms/CMSSignedDataParser.cs
index c5dc795a8..04a6d666b 100644
--- a/crypto/src/cms/CMSSignedDataParser.cs
+++ b/crypto/src/cms/CMSSignedDataParser.cs
@@ -366,7 +366,7 @@ namespace Org.BouncyCastle.Cms
 
 //			gen.AddSigners(parser.GetSignerInfos());
 
-            Platform.Dispose(contentOut);
+            contentOut.Dispose();
 
 			return outStr;
 		}
@@ -415,7 +415,7 @@ namespace Org.BouncyCastle.Cms
 
 			gen.AddSigners(parser.GetSignerInfos());
 
-            Platform.Dispose(contentOut);
+            contentOut.Dispose();
 
             return outStr;
 		}
diff --git a/crypto/src/cms/CMSSignedDataStreamGenerator.cs b/crypto/src/cms/CMSSignedDataStreamGenerator.cs
index 3f2da5f7e..a4e960ba6 100644
--- a/crypto/src/cms/CMSSignedDataStreamGenerator.cs
+++ b/crypto/src/cms/CMSSignedDataStreamGenerator.cs
@@ -621,12 +621,13 @@ namespace Org.BouncyCastle.Cms
 			Stream			dataOutputStream,
 			CmsProcessable	content)
 		{
-			Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream);
-			if (content != null)
+			using (var signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream))
 			{
-				content.Write(signedOut);
-			}
-            Platform.Dispose(signedOut);
+                if (content != null)
+                {
+                    content.Write(signedOut);
+                }
+            }
 		}
 
 		// RFC3852, section 5.1:
@@ -806,7 +807,7 @@ namespace Org.BouncyCastle.Cms
 
             private void DoClose()
             {
-                Platform.Dispose(_out);
+                _out.Dispose();
 
                 // TODO Parent context(s) should really be be closed explicitly
 
diff --git a/crypto/src/cms/CMSTypedStream.cs b/crypto/src/cms/CMSTypedStream.cs
index 7a66f0c74..92e71a20e 100644
--- a/crypto/src/cms/CMSTypedStream.cs
+++ b/crypto/src/cms/CMSTypedStream.cs
@@ -49,7 +49,7 @@ namespace Org.BouncyCastle.Cms
 		public void Drain()
 		{
 			Streams.Drain(_in);
-            Platform.Dispose(_in);
+            _in.Dispose();
 		}
 
 		private class FullReaderStream : FilterStream
diff --git a/crypto/src/crmf/EncryptedValueBuilder.cs b/crypto/src/crmf/EncryptedValueBuilder.cs
index 0154be58c..37f38df1c 100644
--- a/crypto/src/crmf/EncryptedValueBuilder.cs
+++ b/crypto/src/crmf/EncryptedValueBuilder.cs
@@ -112,12 +112,14 @@ namespace Org.BouncyCastle.Crmf
         private EncryptedValue EncryptData(byte[] data)
         {
             MemoryOutputStream bOut = new MemoryOutputStream();
-            Stream eOut = encryptor.BuildCipher(bOut).Stream;
+            var cipher = encryptor.BuildCipher(bOut);
 
             try
             {
-                eOut.Write(data, 0, data.Length);
-                Platform.Dispose(eOut);
+                using (var eOut = cipher.Stream)
+                {
+                    eOut.Write(data, 0, data.Length);
+                }
             }
             catch (IOException e)
             {
diff --git a/crypto/src/crmf/ProofOfPossessionSigningKeyBuilder.cs b/crypto/src/crmf/ProofOfPossessionSigningKeyBuilder.cs
index eed66b083..4cd568e81 100644
--- a/crypto/src/crmf/ProofOfPossessionSigningKeyBuilder.cs
+++ b/crypto/src/crmf/ProofOfPossessionSigningKeyBuilder.cs
@@ -38,11 +38,13 @@ namespace Org.BouncyCastle.Crmf
         {
             IMacFactory fact = generator.Build(password);
 
-            IStreamCalculator<IBlockResult> calc = fact.CreateCalculator();
             byte[] d = _pubKeyInfo.GetDerEncoded();
-            calc.Stream.Write(d, 0, d.Length);
-            calc.Stream.Flush();
-            Platform.Dispose(calc.Stream);
+
+            IStreamCalculator<IBlockResult> calc = fact.CreateCalculator();
+            using (var stream = calc.Stream)
+            {
+                stream.Write(d, 0, d.Length);
+            }
 
             this._publicKeyMAC = new PKMacValue(
                 (AlgorithmIdentifier)fact.AlgorithmDetails,
diff --git a/crypto/src/crypto/io/CipherStream.cs b/crypto/src/crypto/io/CipherStream.cs
index 6802e81d7..1d9a768a1 100644
--- a/crypto/src/crypto/io/CipherStream.cs
+++ b/crypto/src/crypto/io/CipherStream.cs
@@ -268,7 +268,7 @@ namespace Org.BouncyCastle.Crypto.IO
                     m_stream.Write(data, 0, data.Length);
 #endif
 			    }
-                Platform.Dispose(m_stream);
+                m_stream.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/crypto/io/DigestStream.cs b/crypto/src/crypto/io/DigestStream.cs
index ae7fc94de..5d4d8bcb8 100644
--- a/crypto/src/crypto/io/DigestStream.cs
+++ b/crypto/src/crypto/io/DigestStream.cs
@@ -152,7 +152,7 @@ namespace Org.BouncyCastle.Crypto.IO
         {
             if (disposing)
             {
-                Platform.Dispose(m_stream);
+                m_stream.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/crypto/io/MacStream.cs b/crypto/src/crypto/io/MacStream.cs
index c97614289..b47025d5b 100644
--- a/crypto/src/crypto/io/MacStream.cs
+++ b/crypto/src/crypto/io/MacStream.cs
@@ -152,7 +152,7 @@ namespace Org.BouncyCastle.Crypto.IO
         {
             if (disposing)
             {
-                Platform.Dispose(m_stream);
+                m_stream.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/crypto/io/SignerStream.cs b/crypto/src/crypto/io/SignerStream.cs
index fecc0d309..ee7be1cd7 100644
--- a/crypto/src/crypto/io/SignerStream.cs
+++ b/crypto/src/crypto/io/SignerStream.cs
@@ -152,7 +152,7 @@ namespace Org.BouncyCastle.Crypto.IO
         {
             if (disposing)
             {
-                Platform.Dispose(stream);
+                stream.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/crypto/parameters/SkeinParameters.cs b/crypto/src/crypto/parameters/SkeinParameters.cs
index f32ce0532..47b2572aa 100644
--- a/crypto/src/crypto/parameters/SkeinParameters.cs
+++ b/crypto/src/crypto/parameters/SkeinParameters.cs
@@ -225,14 +225,15 @@ namespace Org.BouncyCastle.Crypto.Parameters
 				try
 				{
 					MemoryStream bout = new MemoryStream();
-					StreamWriter outBytes = new StreamWriter(bout, System.Text.Encoding.UTF8);
-					outBytes.Write(date.ToString("YYYYMMDD", CultureInfo.InvariantCulture));
-					outBytes.Write(" ");
-					outBytes.Write(emailAddress);
-					outBytes.Write(" ");
-					outBytes.Write(distinguisher);
-                    Platform.Dispose(outBytes);
-					return Set(PARAM_TYPE_PERSONALISATION, bout.ToArray());
+					using (var outBytes = new StreamWriter(bout, System.Text.Encoding.UTF8))
+					{
+                        outBytes.Write(date.ToString("YYYYMMDD", CultureInfo.InvariantCulture));
+                        outBytes.Write(" ");
+                        outBytes.Write(emailAddress);
+                        outBytes.Write(" ");
+                        outBytes.Write(distinguisher);
+                    }
+                    return Set(PARAM_TYPE_PERSONALISATION, bout.ToArray());
 				}
 				catch (IOException e)
 				{
diff --git a/crypto/src/openpgp/IStreamGenerator.cs b/crypto/src/openpgp/IStreamGenerator.cs
index 379213a66..df8ff75da 100644
--- a/crypto/src/openpgp/IStreamGenerator.cs
+++ b/crypto/src/openpgp/IStreamGenerator.cs
@@ -1,7 +1,9 @@
+using System;
+
 namespace Org.BouncyCastle.Bcpg.OpenPgp
 {
 	public interface IStreamGenerator
+		: IDisposable
 	{
-		void Close();
 	}
 }
diff --git a/crypto/src/openpgp/PgpCompressedDataGenerator.cs b/crypto/src/openpgp/PgpCompressedDataGenerator.cs
index d13d7402b..271dfac7a 100644
--- a/crypto/src/openpgp/PgpCompressedDataGenerator.cs
+++ b/crypto/src/openpgp/PgpCompressedDataGenerator.cs
@@ -1,7 +1,6 @@
 using System;
 using System.IO;
 
-using Org.BouncyCastle.Utilities;
 using Org.BouncyCastle.Utilities.IO.Compression;
 using Org.BouncyCastle.Utilities.Zlib;
 
@@ -149,21 +148,33 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp
 			}
 		}
 
-		/// <summary>Close the compressed object.</summary>summary>
-		public void Close()
-		{
-			if (dOut != null)
-			{
-				if (dOut != pkOut)
-				{
-                    Platform.Dispose(dOut);
-				}
-				dOut = null;
-
-				pkOut.Finish();
-				pkOut.Flush();
-				pkOut = null;
-			}
-		}
+        #region IDisposable
+
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        protected virtual void Dispose(bool disposing)
+        {
+            if (disposing)
+            {
+                if (dOut != null)
+                {
+                    if (dOut != pkOut)
+                    {
+                        dOut.Dispose();
+                    }
+                    dOut = null;
+
+                    pkOut.Finish();
+                    pkOut.Flush();
+                    pkOut = null;
+                }
+            }
+        }
+
+        #endregion
 	}
 }
diff --git a/crypto/src/openpgp/PgpEncryptedDataGenerator.cs b/crypto/src/openpgp/PgpEncryptedDataGenerator.cs
index 69e0d5dbc..b9473a32c 100644
--- a/crypto/src/openpgp/PgpEncryptedDataGenerator.cs
+++ b/crypto/src/openpgp/PgpEncryptedDataGenerator.cs
@@ -2,7 +2,7 @@ using System;
 using System.Collections.Generic;
 using System.Diagnostics;
 using System.IO;
-using Org.BouncyCastle.Asn1;
+
 using Org.BouncyCastle.Asn1.Cryptlib;
 using Org.BouncyCastle.Asn1.EdEC;
 using Org.BouncyCastle.Crypto;
@@ -600,52 +600,55 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp
             return Open(outStr, 0, buffer);
         }
 
-		/// <summary>
-		/// <p>
-		/// Close off the encrypted object - this is equivalent to calling Close() on the stream
-		/// returned by the Open() method.
-		/// </p>
-		/// <p>
-		/// <b>Note</b>: This does not close the underlying output stream, only the stream on top of
-		/// it created by the Open() method.
-		/// </p>
-		/// </summary>
-        public void Close()
+        #region IDisposable
+
+        public void Dispose()
         {
-            if (cOut != null)
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        protected virtual void Dispose(bool disposing)
+        {
+            if (disposing)
             {
-				// TODO Should this all be under the try/catch block?
-                if (digestOut != null)
+                if (cOut != null)
                 {
-                    //
-                    // hand code a mod detection packet
-                    //
-                    BcpgOutputStream bOut = new BcpgOutputStream(
-						digestOut, PacketTag.ModificationDetectionCode, 20);
-
-                    bOut.Flush();
-                    digestOut.Flush();
+				    // TODO Should this all be under the try/catch block?
+                    if (digestOut != null)
+                    {
+                        //
+                        // hand code a mod detection packet
+                        //
+                        BcpgOutputStream bOut = new BcpgOutputStream(
+						    digestOut, PacketTag.ModificationDetectionCode, 20);
+
+                        bOut.Flush();
+                        digestOut.Flush();
+
+					    // TODO
+					    byte[] dig = DigestUtilities.DoFinal(digestOut.WriteDigest);
+					    cOut.Write(dig, 0, dig.Length);
+                    }
 
-					// TODO
-					byte[] dig = DigestUtilities.DoFinal(digestOut.WriteDigest);
-					cOut.Write(dig, 0, dig.Length);
-                }
+				    cOut.Flush();
 
-				cOut.Flush();
+				    try
+                    {
+					    pOut.Write(c.DoFinal());
+                        pOut.Finish();
+                    }
+                    catch (Exception e)
+                    {
+                        throw new IOException(e.Message, e);
+                    }
 
-				try
-                {
-					pOut.Write(c.DoFinal());
-                    pOut.Finish();
-                }
-                catch (Exception e)
-                {
-                    throw new IOException(e.Message, e);
+				    cOut = null;
+				    pOut = null;
                 }
-
-				cOut = null;
-				pOut = null;
             }
-		}
+        }
+
+        #endregion
 	}
 }
diff --git a/crypto/src/openpgp/PgpLiteralDataGenerator.cs b/crypto/src/openpgp/PgpLiteralDataGenerator.cs
index f9a9e7cad..fd59c1ebe 100644
--- a/crypto/src/openpgp/PgpLiteralDataGenerator.cs
+++ b/crypto/src/openpgp/PgpLiteralDataGenerator.cs
@@ -1,6 +1,5 @@
 using System;
 using System.IO;
-using System.Text;
 
 using Org.BouncyCastle.Utilities;
 using Org.BouncyCastle.Utilities.Date;
@@ -163,18 +162,27 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp
 			return Open(outStr, format, file.Name, file.Length, file.LastWriteTime);
         }
 
-		/// <summary>
-		/// Close the literal data packet - this is equivalent to calling Close()
-		/// on the stream returned by the Open() method.
-		/// </summary>
-        public void Close()
+        #region IDisposable
+
+        public void Dispose()
         {
-			if (pkOut != null)
-			{
-				pkOut.Finish();
-				pkOut.Flush();
-				pkOut = null;
-			}
-		}
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        protected virtual void Dispose(bool disposing)
+        {
+            if (disposing)
+            {
+                if (pkOut != null)
+                {
+                    pkOut.Finish();
+                    pkOut.Flush();
+                    pkOut = null;
+                }
+            }
+        }
+
+        #endregion
 	}
 }
diff --git a/crypto/src/openpgp/PgpUtilities.cs b/crypto/src/openpgp/PgpUtilities.cs
index 65f011994..f400d36cc 100644
--- a/crypto/src/openpgp/PgpUtilities.cs
+++ b/crypto/src/openpgp/PgpUtilities.cs
@@ -449,8 +449,8 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp
             {
                 Array.Clear(buf, 0, buf.Length);
 
-                Platform.Dispose(pOut);
-                Platform.Dispose(inputStream);
+                pOut.Dispose();
+                inputStream.Dispose();
             }
         }
 
diff --git a/crypto/src/openpgp/WrappedGeneratorStream.cs b/crypto/src/openpgp/WrappedGeneratorStream.cs
index 6f96dc9b8..c985a7a05 100644
--- a/crypto/src/openpgp/WrappedGeneratorStream.cs
+++ b/crypto/src/openpgp/WrappedGeneratorStream.cs
@@ -8,7 +8,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp
 	internal sealed class WrappedGeneratorStream
 		: FilterStream
 	{
-		private IStreamGenerator m_generator;
+		private readonly IStreamGenerator m_generator;
 
 		internal WrappedGeneratorStream(IStreamGenerator generator, Stream s)
 			: base(s)
@@ -18,14 +18,9 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp
 
         protected override void Dispose(bool disposing)
         {
-			if (m_generator != null)
+			if (disposing)
 			{
-				if (disposing)
-				{
-					m_generator.Close();
-				}
-
-				m_generator = null;
+				m_generator.Dispose();
 			}
 
 			Detach(disposing);
diff --git a/crypto/src/openssl/PEMReader.cs b/crypto/src/openssl/PEMReader.cs
index 1ba7165b3..d2354dbe3 100644
--- a/crypto/src/openssl/PEMReader.cs
+++ b/crypto/src/openssl/PEMReader.cs
@@ -29,7 +29,7 @@ namespace Org.BouncyCastle.OpenSsl
     * Certificates will be returned using the appropriate java.security type.</p>
     */
     public class PemReader
-        : Org.BouncyCastle.Utilities.IO.Pem.PemReader
+        : Utilities.IO.Pem.PemReader
     {
         //private static readonly Dictionary<string, PemObjectParser> Parsers = new Dictionary<string, PemObjectParser>();
 
diff --git a/crypto/src/openssl/PEMWriter.cs b/crypto/src/openssl/PEMWriter.cs
index e6332ec02..043869cc3 100644
--- a/crypto/src/openssl/PEMWriter.cs
+++ b/crypto/src/openssl/PEMWriter.cs
@@ -23,8 +23,8 @@ namespace Org.BouncyCastle.OpenSsl
 			}
 			catch (PemGenerationException e)
 			{
-				if (e.InnerException is IOException)
-					throw (IOException)e.InnerException;
+				if (e.InnerException is IOException inner)
+					throw inner;
 
 				throw e;
 			}
diff --git a/crypto/src/pkcs/Pkcs10CertificationRequest.cs b/crypto/src/pkcs/Pkcs10CertificationRequest.cs
index 59b5b51ed..12151a001 100644
--- a/crypto/src/pkcs/Pkcs10CertificationRequest.cs
+++ b/crypto/src/pkcs/Pkcs10CertificationRequest.cs
@@ -345,10 +345,10 @@ namespace Org.BouncyCastle.Pkcs
                 byte[] b = reqInfo.GetDerEncoded();
 
                 IStreamCalculator<IVerifier> streamCalculator = verifier.CreateCalculator();
-
-                streamCalculator.Stream.Write(b, 0, b.Length);
-
-                Platform.Dispose(streamCalculator.Stream);
+                using (var stream = streamCalculator.Stream)
+                {
+                    stream.Write(b, 0, b.Length);
+                }
 
                 return streamCalculator.GetResult().IsVerified(sigBits.GetOctets());
             }
diff --git a/crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs b/crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs
index 5882dee38..e18619c18 100644
--- a/crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs
+++ b/crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs
@@ -91,9 +91,11 @@ namespace Org.BouncyCastle.Pkcs
 
                 ICipher encIn = decryptorBuilder.BuildCipher(new MemoryInputStream(encryptedPrivateKeyInfo.GetEncryptedData()));
 
-                Stream strm = encIn.Stream;
-                byte[] data = Streams.ReadAll(encIn.Stream);
-                Platform.Dispose(strm);
+                byte[] data;
+                using (var strm = encIn.Stream)
+                {
+                    data = Streams.ReadAll(encIn.Stream);
+                }
 
                 return PrivateKeyInfo.GetInstance(data);
             }
diff --git a/crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs b/crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs
index 8f751492f..2556a947f 100644
--- a/crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs
+++ b/crypto/src/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs
@@ -36,11 +36,13 @@ namespace Org.BouncyCastle.Pkcs
                 ICipher cOut = encryptor.BuildCipher(bOut);
                 byte[] keyData = privateKeyInfo.GetEncoded();
 
-                Stream str = cOut.Stream;
-                str.Write(keyData, 0, keyData.Length);
-                Platform.Dispose(str);
+                using (var str = cOut.Stream)
+                {
+                    str.Write(keyData, 0, keyData.Length);
+                }
 
-                return new Pkcs8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray()));
+                return new Pkcs8EncryptedPrivateKeyInfo(
+                    new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray()));
             }
             catch (IOException)
             {
diff --git a/crypto/src/pkix/PkixCertPath.cs b/crypto/src/pkix/PkixCertPath.cs
index 95280173a..7f04b1b63 100644
--- a/crypto/src/pkix/PkixCertPath.cs
+++ b/crypto/src/pkix/PkixCertPath.cs
@@ -352,16 +352,16 @@ namespace Org.BouncyCastle.Pkix
             else if (Platform.EqualsIgnoreCase(encoding, "PEM"))
 			{
 				MemoryStream bOut = new MemoryStream();
-				PemWriter pWrt = new PemWriter(new StreamWriter(bOut));
 
 				try
 				{
-					foreach (var cert in m_certificates)
+					using (var pWrt = new PemWriter(new StreamWriter(bOut)))
 					{
-						pWrt.WriteObject(cert);
-					}
-
-                    Platform.Dispose(pWrt.Writer);
+                        foreach (var cert in m_certificates)
+                        {
+                            pWrt.WriteObject(cert);
+                        }
+                    }
 				}
 				catch (Exception)
 				{
diff --git a/crypto/src/tls/CertificateUrl.cs b/crypto/src/tls/CertificateUrl.cs
index 822745e4e..46f8659f8 100644
--- a/crypto/src/tls/CertificateUrl.cs
+++ b/crypto/src/tls/CertificateUrl.cs
@@ -109,7 +109,7 @@ namespace Org.BouncyCastle.Tls
 
                 WriteTo(output);
 
-                Platform.Dispose(this);
+                Dispose();
             }
         }
     }
diff --git a/crypto/src/tls/HandshakeMessageOutput.cs b/crypto/src/tls/HandshakeMessageOutput.cs
index 0d8f15018..af0545e9f 100644
--- a/crypto/src/tls/HandshakeMessageOutput.cs
+++ b/crypto/src/tls/HandshakeMessageOutput.cs
@@ -84,7 +84,7 @@ namespace Org.BouncyCastle.Tls
 
             clientProtocol.WriteHandshakeMessage(buf, 0, count);
 
-            Platform.Dispose(this);
+            Dispose();
         }
     }
 }
diff --git a/crypto/src/tls/RecordStream.cs b/crypto/src/tls/RecordStream.cs
index a5926d05b..8dc2a30ce 100644
--- a/crypto/src/tls/RecordStream.cs
+++ b/crypto/src/tls/RecordStream.cs
@@ -359,7 +359,7 @@ namespace Org.BouncyCastle.Tls
             IOException io = null;
             try
             {
-                Platform.Dispose(m_input);
+                m_input.Dispose();
             }
             catch (IOException e)
             {
@@ -368,7 +368,7 @@ namespace Org.BouncyCastle.Tls
 
             try
             {
-                Platform.Dispose(m_output);
+                m_output.Dispose();
             }
             catch (IOException e)
             {
diff --git a/crypto/src/tls/TlsUtilities.cs b/crypto/src/tls/TlsUtilities.cs
index 463928ba6..e1a8ead58 100644
--- a/crypto/src/tls/TlsUtilities.cs
+++ b/crypto/src/tls/TlsUtilities.cs
@@ -2158,7 +2158,7 @@ namespace Org.BouncyCastle.Tls
 
             buf.CopyInputTo(output);
 
-            Platform.Dispose(output);
+            output.Dispose();
         }
 
         internal static DigitallySigned GenerateCertificateVerifyClient(TlsClientContext clientContext,
diff --git a/crypto/src/tsp/TimeStampTokenGenerator.cs b/crypto/src/tsp/TimeStampTokenGenerator.cs
index 930463ca3..c2aae37e2 100644
--- a/crypto/src/tsp/TimeStampTokenGenerator.cs
+++ b/crypto/src/tsp/TimeStampTokenGenerator.cs
@@ -81,12 +81,14 @@ namespace Org.BouncyCastle.Tsp
 
             try
             {
-                IStreamCalculator<IBlockResult> calculator = digestCalculator.CreateCalculator();
-                Stream stream = calculator.Stream;
                 byte[] certEnc = assocCert.GetEncoded();
-                stream.Write(certEnc, 0, certEnc.Length);
-                stream.Flush();
-                Platform.Dispose(stream);
+
+                IStreamCalculator<IBlockResult> calculator = digestCalculator.CreateCalculator();
+
+                using (var stream = calculator.Stream)
+                {
+                    stream.Write(certEnc, 0, certEnc.Length);
+                }
 
                 if (((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm.Equals(OiwObjectIdentifiers.IdSha1))
                 {
diff --git a/crypto/src/util/Platform.cs b/crypto/src/util/Platform.cs
index 78ff6cee4..a78153b8c 100644
--- a/crypto/src/util/Platform.cs
+++ b/crypto/src/util/Platform.cs
@@ -26,11 +26,6 @@ namespace Org.BouncyCastle.Utilities
             }
         }
 
-        internal static void Dispose(IDisposable d)
-        {
-            d.Dispose();
-        }
-
         internal static int IndexOf(string source, char value)
         {
             return InvariantCompareInfo.IndexOf(source, value, CompareOptions.Ordinal);
diff --git a/crypto/src/util/bzip2/CBZip2InputStream.cs b/crypto/src/util/bzip2/CBZip2InputStream.cs
index 7879f28af..08760f547 100644
--- a/crypto/src/util/bzip2/CBZip2InputStream.cs
+++ b/crypto/src/util/bzip2/CBZip2InputStream.cs
@@ -258,7 +258,7 @@ namespace Org.BouncyCastle.Utilities.Bzip2
             {
                 if (this.bsStream != null)
                 {
-                    Platform.Dispose(this.bsStream);
+                    this.bsStream.Dispose();
                     this.bsStream = null;
                 }
             }
diff --git a/crypto/src/util/bzip2/CBZip2OutputStream.cs b/crypto/src/util/bzip2/CBZip2OutputStream.cs
index b896f36c6..d1400c7c4 100644
--- a/crypto/src/util/bzip2/CBZip2OutputStream.cs
+++ b/crypto/src/util/bzip2/CBZip2OutputStream.cs
@@ -441,7 +441,7 @@ namespace Org.BouncyCastle.Utilities.Bzip2
                 {
                     Finish();
                     closed = true;
-                    Platform.Dispose(this.bsStream);
+                    this.bsStream.Dispose();
                 }
             }
             base.Dispose(disposing);
diff --git a/crypto/src/util/io/TeeInputStream.cs b/crypto/src/util/io/TeeInputStream.cs
index 3d45bb4f1..7815fde76 100644
--- a/crypto/src/util/io/TeeInputStream.cs
+++ b/crypto/src/util/io/TeeInputStream.cs
@@ -22,8 +22,8 @@ namespace Org.BouncyCastle.Utilities.IO
         {
             if (disposing)
             {
-                Platform.Dispose(input);
-                Platform.Dispose(tee);
+                input.Dispose();
+                tee.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/util/io/TeeOutputStream.cs b/crypto/src/util/io/TeeOutputStream.cs
index fc213ae55..1762d6f52 100644
--- a/crypto/src/util/io/TeeOutputStream.cs
+++ b/crypto/src/util/io/TeeOutputStream.cs
@@ -22,8 +22,8 @@ namespace Org.BouncyCastle.Utilities.IO
         {
             if (disposing)
             {
-                Platform.Dispose(output);
-                Platform.Dispose(tee);
+                output.Dispose();
+                tee.Dispose();
             }
             base.Dispose(disposing);
         }
diff --git a/crypto/src/util/io/pem/PemReader.cs b/crypto/src/util/io/pem/PemReader.cs
index cd19e95b8..77b457338 100644
--- a/crypto/src/util/io/pem/PemReader.cs
+++ b/crypto/src/util/io/pem/PemReader.cs
@@ -6,8 +6,8 @@ using Org.BouncyCastle.Utilities.Encoders;
 
 namespace Org.BouncyCastle.Utilities.IO.Pem
 {
-
 	public class PemReader
+		: IDisposable
 	{		
 		private readonly TextReader reader;
 		private readonly MemoryStream buffer;
@@ -17,17 +17,30 @@ namespace Org.BouncyCastle.Utilities.IO.Pem
 
 		public PemReader(TextReader reader)
 		{
-			if (reader == null)
-				throw new ArgumentNullException("reader");
+			this.reader = reader ?? throw new ArgumentNullException(nameof(reader));
+            this.buffer = new MemoryStream();
+            this.textBuffer = new StreamWriter(buffer);
+		}
 
+        #region IDisposable
 
-			buffer = new MemoryStream();
-			textBuffer = new StreamWriter(buffer);
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
 
-			this.reader = reader;
-		}
+        protected virtual void Dispose(bool disposing)
+        {
+            if (disposing)
+            {
+                reader.Dispose();
+            }
+        }
+
+        #endregion
 
-		public TextReader Reader
+        public TextReader Reader
 		{
 			get { return reader; }
 		}
diff --git a/crypto/src/util/io/pem/PemWriter.cs b/crypto/src/util/io/pem/PemWriter.cs
index fbb8b0f2d..ee92556c7 100644
--- a/crypto/src/util/io/pem/PemWriter.cs
+++ b/crypto/src/util/io/pem/PemWriter.cs
@@ -9,13 +9,14 @@ namespace Org.BouncyCastle.Utilities.IO.Pem
 	* A generic PEM writer, based on RFC 1421
 	*/
 	public class PemWriter
+		: IDisposable
 	{
 		private const int LineLength = 64;
 
 		private readonly TextWriter	writer;
 		private readonly int		nlLength;
 		private char[]				buf = new char[LineLength];
-		
+
 		/**
 		 * Base constructor.
 		 *
@@ -23,14 +24,29 @@ namespace Org.BouncyCastle.Utilities.IO.Pem
 		 */
 		public PemWriter(TextWriter writer)
 		{
-			if (writer == null)
-				throw new ArgumentNullException("writer");
-
-			this.writer = writer;
-			this.nlLength = Environment.NewLine.Length;
+			this.writer = writer ?? throw new ArgumentNullException(nameof(writer));
+            this.nlLength = Environment.NewLine.Length;
 		}
 
-		public TextWriter Writer
+        #region IDisposable
+
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        protected virtual void Dispose(bool disposing)
+        {
+            if (disposing)
+            {
+                writer.Dispose();
+            }
+        }
+
+        #endregion
+
+        public TextWriter Writer
 		{
 			get { return writer; }
 		}
@@ -115,5 +131,5 @@ namespace Org.BouncyCastle.Utilities.IO.Pem
 		{
 			writer.WriteLine("-----END " + type + "-----");
 		}
-	}
+    }
 }
diff --git a/crypto/src/util/zlib/ZInputStream.cs b/crypto/src/util/zlib/ZInputStream.cs
index 0433a0182..de1c27202 100644
--- a/crypto/src/util/zlib/ZInputStream.cs
+++ b/crypto/src/util/zlib/ZInputStream.cs
@@ -123,7 +123,7 @@ namespace Org.BouncyCastle.Utilities.Zlib
 			    if (!closed)
                 {
                     closed = true;
-                    Platform.Dispose(input);
+                    input.Dispose();
                 }
             }
             base.Dispose(disposing);
diff --git a/crypto/src/util/zlib/ZOutputStream.cs b/crypto/src/util/zlib/ZOutputStream.cs
index 51a5050dd..ecf33cddf 100644
--- a/crypto/src/util/zlib/ZOutputStream.cs
+++ b/crypto/src/util/zlib/ZOutputStream.cs
@@ -158,7 +158,7 @@ namespace Org.BouncyCastle.Utilities.Zlib
                     {
                         this.closed = true;
                         End();
-                        Platform.Dispose(output);
+                        output.Dispose();
                         output = null;
                     }
                 }
diff --git a/crypto/src/x509/X509Certificate.cs b/crypto/src/x509/X509Certificate.cs
index 510f95b01..5b800efe5 100644
--- a/crypto/src/x509/X509Certificate.cs
+++ b/crypto/src/x509/X509Certificate.cs
@@ -680,15 +680,13 @@ namespace Org.BouncyCastle.X509
             if (!IsAlgIDEqual(c.SignatureAlgorithm, c.TbsCertificate.Signature))
                 throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
 
-            Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
+            byte[] b = GetTbsCertificate();
 
             IStreamCalculator<IVerifier> streamCalculator = verifier.CreateCalculator();
-
-            byte[] b = this.GetTbsCertificate();
-
-            streamCalculator.Stream.Write(b, 0, b.Length);
-
-            Platform.Dispose(streamCalculator.Stream);
+            using (var stream = streamCalculator.Stream)
+            {
+                stream.Write(b, 0, b.Length);
+            }
 
             if (!streamCalculator.GetResult().IsVerified(this.GetSignature()))
                 throw new InvalidKeyException("Public key presented not for certificate signature");
diff --git a/crypto/src/x509/X509Crl.cs b/crypto/src/x509/X509Crl.cs
index 265c2293c..db13f4f2f 100644
--- a/crypto/src/x509/X509Crl.cs
+++ b/crypto/src/x509/X509Crl.cs
@@ -130,17 +130,15 @@ namespace Org.BouncyCastle.X509
             if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature))
                 throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
 
-            Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
+            byte[] b = GetTbsCertList();
 
             IStreamCalculator<IVerifier> streamCalculator = verifier.CreateCalculator();
+			using (var stream = streamCalculator.Stream)
+			{
+				stream.Write(b, 0, b.Length);
+            }
 
-            byte[] b = this.GetTbsCertList();
-
-            streamCalculator.Stream.Write(b, 0, b.Length);
-
-            Platform.Dispose(streamCalculator.Stream);
-
-            if (!streamCalculator.GetResult().IsVerified(this.GetSignature()))
+            if (!streamCalculator.GetResult().IsVerified(GetSignature()))
                 throw new InvalidKeyException("CRL does not verify with supplied public key.");
         }
 
diff --git a/crypto/src/x509/X509V2AttributeCertificate.cs b/crypto/src/x509/X509V2AttributeCertificate.cs
index fbb4fe20f..61702aebd 100644
--- a/crypto/src/x509/X509V2AttributeCertificate.cs
+++ b/crypto/src/x509/X509V2AttributeCertificate.cs
@@ -192,9 +192,10 @@ namespace Org.BouncyCastle.X509
 			{
                 byte[] b = this.cert.ACInfo.GetEncoded();
 
-                streamCalculator.Stream.Write(b, 0, b.Length);
-
-                Platform.Dispose(streamCalculator.Stream);
+				using (var stream = streamCalculator.Stream)
+				{
+                    stream.Write(b, 0, b.Length);
+                }
             }
 			catch (IOException e)
 			{
diff --git a/crypto/test/src/crypto/io/test/PemReaderTest.cs b/crypto/test/src/crypto/io/test/PemReaderTest.cs
index c2d4dfb98..8e8215a9c 100644
--- a/crypto/test/src/crypto/io/test/PemReaderTest.cs
+++ b/crypto/test/src/crypto/io/test/PemReaderTest.cs
@@ -19,14 +19,17 @@ namespace Org.BouncyCastle.Crypto.IO.Tests
         {
             string raw = "-----BEGIN CERTIFICATE REQUEST----- MIIBkTCB+wIBADAUMRIwEAYDVQQDDAlUZXN0MlNBTnMwgZ8wDQYJKoZIhvcNAQEB BQADgY0AMIGJAoGBAPPPH7W8LqBMCwSu/MsmCeSCfBzMEp4k+aZmeKw8EQD1R3FK WtPy/LcaUyQhyIeNPFAH8JEz0dJRJjleFL8G5pv7c2YXjBmIfbF/W2eETBIohMDP pWOqKYiT1mqzw25rP1VuXGXaSfN22RReomUd9O2GuEkaqz5x5iTRD6aLmDoJAgMB AAGgPjA8BgkqhkiG9w0BCQ4xLzAtMCsGA1UdEQQkMCKCD3NhbjEudGVzdC5sb2Nh bIIPc2FuMi50ZXN0LmxvY2FsMA0GCSqGSIb3DQEBCwUAA4GBAOacp+9s7/jpmSTA ORvx4nsDwBsY4VLeuPUc2gYmHqfVgrCCSHKPQtQge0P5atudbo+q8Fn+/5JnJR6/ JaooICY3M+/QVrvzvV30i5W8aEIERfXsEIcFyVxv24p6SbrGAcSjwpqvgAf0z82F D3f1qdFATb9HAFsuD/J0HexTFDvB -----END CERTIFICATE REQUEST-----";
 
-            PemReader pemReader = new PemReader(new StringReader(raw));
-            PemObject item = pemReader.ReadPemObject();
+            using (var pemReader = new PemReader(new StringReader(raw)))
+            {
+                PemObject item = pemReader.ReadPemObject();
 
-            Asn1.Pkcs.CertificationRequest pkcs10 = Pkcs10CertificationRequest.GetInstance(Asn1Sequence.GetInstance(item.Content));
-            string subject = pkcs10.GetCertificationRequestInfo().Subject.ToString();
+                Asn1.Pkcs.CertificationRequest pkcs10 = Asn1.Pkcs.CertificationRequest.GetInstance(
+                    Asn1Sequence.GetInstance(item.Content));
+                string subject = pkcs10.GetCertificationRequestInfo().Subject.ToString();
 
-            Assert.AreEqual("CERTIFICATE REQUEST", item.Type);
-            Assert.AreEqual("CN=Test2SANs", subject);
+                Assert.AreEqual("CERTIFICATE REQUEST", item.Type);
+                Assert.AreEqual("CN=Test2SANs", subject);
+            }
         }
 
         [Test]
@@ -77,11 +80,13 @@ namespace Org.BouncyCastle.Crypto.IO.Tests
                 "tj3BYd+M1x+f59Nk1gIgZDiPbzI3K33PKJPl5udwxakSBLBLpSl7I9+F8hhEi9I=\n" +
                 "-----END CERTIFICATE-----\n";
 
-            PemReader pemReader = new PemReader(new StringReader(test));
-            PemObject item = pemReader.ReadPemObject();
-            Assert.AreEqual("CERTIFICATE", item.Type);
-            X509CertificateStructure cert = X509CertificateStructure.GetInstance(Asn1Sequence.GetInstance(item.Content));
-            Assert.AreEqual("CN=estExampleCA", cert.Issuer.ToString());
+            using (var pemReader = new PemReader(new StringReader(test)))
+            {
+                PemObject item = pemReader.ReadPemObject();
+                Assert.AreEqual("CERTIFICATE", item.Type);
+                X509CertificateStructure cert = X509CertificateStructure.GetInstance(Asn1Sequence.GetInstance(item.Content));
+                Assert.AreEqual("CN=estExampleCA", cert.Issuer.ToString());
+            }
         }
 
         [Test]
@@ -104,8 +109,12 @@ namespace Org.BouncyCastle.Crypto.IO.Tests
                 "tj3BYd+M1x+f59Nk1gIgZDiPbzI3K33PKJPl5udwxakSBLBLpSl7I9+F8hhEi9I=\n" +
                 "-----END CERTIFICATE-----\n";
 
-            PemReader pemReader = new PemReader(new StringReader(test));
-            PemObject item = pemReader.ReadPemObject();
+            PemObject item;
+            using (var pemReader = new PemReader(new StringReader(test)))
+            {
+                item = pemReader.ReadPemObject();
+            }
+
             Assert.AreEqual("CERTIFICATE", item.Type);
             X509CertificateStructure cert = X509CertificateStructure.GetInstance(Asn1Sequence.GetInstance(item.Content));
             Assert.AreEqual("CN=estExampleCA", cert.Issuer.ToString());
@@ -120,8 +129,8 @@ namespace Org.BouncyCastle.Crypto.IO.Tests
 
             })
             {
-                Assert.AreEqual(items[0], ((PemHeader)item.Headers[t]).Name);
-                Assert.AreEqual(items[1], ((PemHeader)item.Headers[t]).Value);
+                Assert.AreEqual(items[0], item.Headers[t].Name);
+                Assert.AreEqual(items[1], item.Headers[t].Value);
                 t++;
             }
 
@@ -141,11 +150,13 @@ namespace Org.BouncyCastle.Crypto.IO.Tests
                 "tj3BYd+M1x+f59Nk1gIgZDiPbzI3K33PKJPl5udwxakSBLBLpSl7I9+F8hhEi9I=" +
                 "-----END CERTIFICATE-----";
 
-            PemReader pemReader = new PemReader(new StringReader(test));
-            PemObject item = pemReader.ReadPemObject();
-            Assert.AreEqual("CERTIFICATE", item.Type);
-            X509CertificateStructure cert = X509CertificateStructure.GetInstance(Asn1Sequence.GetInstance(item.Content));
-            Assert.AreEqual("CN=estExampleCA", cert.Issuer.ToString());
+            using (var pemReader = new PemReader(new StringReader(test)))
+            {
+                PemObject item = pemReader.ReadPemObject();
+                Assert.AreEqual("CERTIFICATE", item.Type);
+                X509CertificateStructure cert = X509CertificateStructure.GetInstance(Asn1Sequence.GetInstance(item.Content));
+                Assert.AreEqual("CN=estExampleCA", cert.Issuer.ToString());
+            }
         }
     }
 }
diff --git a/crypto/test/src/openpgp/test/DSA2Test.cs b/crypto/test/src/openpgp/test/DSA2Test.cs
index 54c2cb2b5..dc7dffe81 100644
--- a/crypto/test/src/openpgp/test/DSA2Test.cs
+++ b/crypto/test/src/openpgp/test/DSA2Test.cs
@@ -144,7 +144,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
 				sGen.Update((byte)ch);
 			}
 
-			lGen.Close();
+			lGen.Dispose();
 
 			sGen.Generate().Encode(bcOut);
 
diff --git a/crypto/test/src/openpgp/test/PGPCompressionTest.cs b/crypto/test/src/openpgp/test/PGPCompressionTest.cs
index 456cf1537..21f1616af 100644
--- a/crypto/test/src/openpgp/test/PGPCompressionTest.cs
+++ b/crypto/test/src/openpgp/test/PGPCompressionTest.cs
@@ -74,19 +74,19 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
 
 			if (streamClose)
 			{
-				os.Close();
+				os.Dispose();
 			}
 			else
 			{
-				cPacket.Close();
+				cPacket.Dispose();
 			}
 
 			ValidateData(data, bOut.ToArray());
 
 			try
 			{
-				os.Close();
-				cPacket.Close();
+				os.Dispose();
+				cPacket.Dispose();
 			}
 			catch (Exception)
 			{
diff --git a/crypto/test/src/openpgp/test/PGPDSAElGamalTest.cs b/crypto/test/src/openpgp/test/PGPDSAElGamalTest.cs
index 07c4d7eb6..a5de29622 100644
--- a/crypto/test/src/openpgp/test/PGPDSAElGamalTest.cs
+++ b/crypto/test/src/openpgp/test/PGPDSAElGamalTest.cs
@@ -157,11 +157,11 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
 				sGen.Update((byte) ch);
 			}
 
-			lGen.Close();
+			lGen.Dispose();
 
 			sGen.Generate().Encode(bcOut);
 
-			cGen.Close();
+			cGen.Dispose();
 
 			//
 			// verify Generated signature
diff --git a/crypto/test/src/openpgp/test/PGPDSATest.cs b/crypto/test/src/openpgp/test/PGPDSATest.cs
index 70aca8e1f..357753a3c 100644
--- a/crypto/test/src/openpgp/test/PGPDSATest.cs
+++ b/crypto/test/src/openpgp/test/PGPDSATest.cs
@@ -321,11 +321,11 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
                 sGen.Update((byte)ch);
             }
 
-            lGen.Close();
+            lGen.Dispose();
 
             sGen.Generate().Encode(bcOut);
 
-            cGen.Close();
+            cGen.Dispose();
 
             PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray());
             PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();
@@ -446,11 +446,11 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
                 sGen.Update((byte)ch);
             }
 
-			lGen.Close();
+			lGen.Dispose();
 
 			sGen.Generate().Encode(bcOut);
 
-            cGen.Close();
+            cGen.Dispose();
 
             //
             // verify Generated signature - canconical text
diff --git a/crypto/test/src/openpgp/test/PGPPBETest.cs b/crypto/test/src/openpgp/test/PGPPBETest.cs
index 6b3718ecc..db7782144 100644
--- a/crypto/test/src/openpgp/test/PGPPBETest.cs
+++ b/crypto/test/src/openpgp/test/PGPPBETest.cs
@@ -194,7 +194,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
 			cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length);
 			cOut.Write(bOutData, 0, bOutData.Length);
 
-			cPk.Close();
+			cPk.Dispose();
 
 			data = DecryptMessage(cbOut.ToArray());
 
@@ -226,9 +226,9 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
                 new byte[16]);
 
             ldOut.Write(test, 0, test.Length);
-            lData.Close();
+            lData.Dispose();
 
-			comData.Close();
+			comData.Dispose();
             cbOut = new UncloseableMemoryStream();
             cPk = new PgpEncryptedDataGenerator(
 				SymmetricKeyAlgorithmTag.Cast5, rand);
@@ -241,7 +241,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
                 cOut.Write(tmp, 0, tmp.Length);
             }
 
-			cPk.Close();
+			cPk.Dispose();
 
 			data = DecryptMessage(cbOut.ToArray());
             if (!Arrays.AreEqual(data, test))
@@ -261,7 +261,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
             cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
             bOutData = bOut.ToArray();
             cOut.Write(bOutData, 0, bOutData.Length);
-            cPk.Close();
+            cPk.Dispose();
 
 			data = DecryptMessage(cbOut.ToArray());
             if (!Arrays.AreEqual(data, test))
diff --git a/crypto/test/src/openpgp/test/PGPPacketTest.cs b/crypto/test/src/openpgp/test/PGPPacketTest.cs
index f2b523d04..737ba6578 100644
--- a/crypto/test/src/openpgp/test/PGPPacketTest.cs
+++ b/crypto/test/src/openpgp/test/PGPPacketTest.cs
@@ -34,7 +34,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
 
 				outputStream.Write(buf, 0, i);
 
-                generator.Close();
+                generator.Dispose();
 
                 PgpObjectFactory fact = new PgpObjectFactory(bOut.ToArray());
 
diff --git a/crypto/test/src/openpgp/test/PGPRSATest.cs b/crypto/test/src/openpgp/test/PGPRSATest.cs
index fa573de65..e3ed2f021 100644
--- a/crypto/test/src/openpgp/test/PGPRSATest.cs
+++ b/crypto/test/src/openpgp/test/PGPRSATest.cs
@@ -363,7 +363,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
 
             lOut.Write(text, 0, text.Length);
 
-            lGen.Close();
+            lGen.Dispose();
 
             byte[] bytes = bOut.ToArray();
 
diff --git a/crypto/test/src/openpgp/test/PGPSignatureTest.cs b/crypto/test/src/openpgp/test/PGPSignatureTest.cs
index ea9df9567..2ca0aef0a 100644
--- a/crypto/test/src/openpgp/test/PGPSignatureTest.cs
+++ b/crypto/test/src/openpgp/test/PGPSignatureTest.cs
@@ -857,7 +857,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
             lOut.Write(TEST_DATA, 0, TEST_DATA.Length);
             sGen.Update(TEST_DATA);
 
-            lGen.Close();
+            lGen.Dispose();
 
             sGen.Generate().Encode(bOut);
 
@@ -898,7 +898,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
             lOut.Write(data, 0, data.Length);
             sGen.Update(data);
 
-            lGen.Close();
+            lGen.Dispose();
 
             PgpSignature sig = sGen.Generate();
 
@@ -953,7 +953,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
             lOut.Write(TEST_DATA, 0, TEST_DATA.Length);
             sGen.Update(TEST_DATA);
 
-            lGen.Close();
+            lGen.Dispose();
 
             sGen.Generate().Encode(bOut);
 
@@ -993,7 +993,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
             lOut.Write(data, 0, data.Length);
             sGen.Update(data);
 
-            lGen.Close();
+            lGen.Dispose();
 
             PgpSignature sig = sGen.Generate();
 
diff --git a/crypto/test/src/openssl/test/AllTests.cs b/crypto/test/src/openssl/test/AllTests.cs
index c6416f9db..fd88bfcdf 100644
--- a/crypto/test/src/openssl/test/AllTests.cs
+++ b/crypto/test/src/openssl/test/AllTests.cs
@@ -44,23 +44,24 @@ namespace Org.BouncyCastle.OpenSsl.Tests
 
 		private void EncryptedTest(AsymmetricKeyParameter privKey, string algorithm)
 		{
-			StringWriter sw = new StringWriter();
-			PemWriter pWrt = new PemWriter(sw);
 			Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey, algorithm);
 			pkcs8.Password = "hello".ToCharArray();
 
-			pWrt.WriteObject(pkcs8);
-			pWrt.Writer.Close();
+            StringWriter sw = new StringWriter();
+			using (var pWrt = new PemWriter(sw))
+			{
+                pWrt.WriteObject(pkcs8);
+            }
 
 			string result = sw.ToString();
 
-			PemReader pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray()));
+			using (var pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray())))
+			{
+                AsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject();
 
-			AsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject();
-			pRd.Reader.Close();
-
-			Assert.AreEqual(privKey, rdKey);
-		}
+                Assert.AreEqual(privKey, rdKey);
+            }
+        }
 
 		[Test]
 		public void TestPkcs8Plain()
@@ -69,22 +70,22 @@ namespace Org.BouncyCastle.OpenSsl.Tests
 			kpGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
 
 			AsymmetricKeyParameter privKey = kpGen.GenerateKeyPair().Private;
+            Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey);
 
-			StringWriter sw = new StringWriter();
-			PemWriter pWrt = new PemWriter(sw);
-
-			Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey);
-			pWrt.WriteObject(pkcs8);
-			pWrt.Writer.Close();
+            StringWriter sw = new StringWriter();
+			using (var pWrt = new PemWriter(sw))
+			{
+                pWrt.WriteObject(pkcs8);
+            }
 
 			string result = sw.ToString();
 
-			PemReader pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray()));
-
-			AsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject();
-			pRd.Reader.Close();
+			using (var pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray())))
+			{
+                AsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject();
 
-			Assert.AreEqual(privKey, rdKey);
-		}
+                Assert.AreEqual(privKey, rdKey);
+            }
+        }
 	}
 }
diff --git a/crypto/test/src/openssl/test/ReaderTest.cs b/crypto/test/src/openssl/test/ReaderTest.cs
index 8cb66d6a6..e8b3dccea 100644
--- a/crypto/test/src/openssl/test/ReaderTest.cs
+++ b/crypto/test/src/openssl/test/ReaderTest.cs
@@ -53,8 +53,8 @@ namespace Org.BouncyCastle.OpenSsl.Tests
                 "-----END PRIVATE KEY-----";
 
             using (var textReader = new StringReader(data))
+            using (var pemReader = new PemReader(textReader))
             {
-                var pemReader = new PemReader(textReader);
                 var pemObj = pemReader.ReadPemObject();
                 PrivateKeyFactory.CreateKey(pemObj.Content);
             }
@@ -63,35 +63,37 @@ namespace Org.BouncyCastle.OpenSsl.Tests
         public override void PerformTest()
         {
             IPasswordFinder pGet = new Password("secret".ToCharArray());
-            PemReader pemRd = OpenPemResource("test.pem", pGet);
-            AsymmetricCipherKeyPair pair;
-
-            object o;
-            while ((o = pemRd.ReadObject()) != null)
+            using (var pemRd = OpenPemResource("test.pem", pGet))
             {
-//				if (o is AsymmetricCipherKeyPair)
-//				{
-//					ackp = (AsymmetricCipherKeyPair)o;
-//
-//					Console.WriteLine(ackp.Public);
-//					Console.WriteLine(ackp.Private);
-//				}
-//				else
-//				{
-//					Console.WriteLine(o.ToString());
-//				}
+                object o;
+                while ((o = pemRd.ReadObject()) != null)
+                {
+                    //if (o is AsymmetricCipherKeyPair)
+                    //{
+                    //    ackp = (AsymmetricCipherKeyPair)o;
+
+                    //    Console.WriteLine(ackp.Public);
+                    //    Console.WriteLine(ackp.Private);
+                    //}
+                    //else
+                    //{
+                    //    Console.WriteLine(o.ToString());
+                    //}
+                }
             }
 
             //
             // pkcs 7 data
             //
-            pemRd = OpenPemResource("pkcs7.pem", null);
-
-            ContentInfo d = (ContentInfo)pemRd.ReadObject();    
-    
-            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
+            ContentInfo d;
+            using (var pemRd = OpenPemResource("pkcs7.pem", null))
             {
-                Fail("failed envelopedData check");
+                d = (ContentInfo)pemRd.ReadObject();
+
+                if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
+                {
+                    Fail("failed envelopedData check");
+                }
             }
 
             /*
@@ -148,7 +150,7 @@ namespace Org.BouncyCastle.OpenSsl.Tests
                 768,
                 25));
 
-            pair = kpGen.GenerateKeyPair();
+            AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair();
 
             keyPairTest("RSA", pair);
 
@@ -171,19 +173,20 @@ namespace Org.BouncyCastle.OpenSsl.Tests
             // PKCS7
             //
             MemoryStream bOut = new MemoryStream();
-            PemWriter pWrt = new PemWriter(new StreamWriter(bOut));
-
-            pWrt.WriteObject(d);
-            pWrt.Writer.Close();
-
-            pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
-            d = (ContentInfo)pemRd.ReadObject();    
-
-            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
+            using (var pWrt = new PemWriter(new StreamWriter(bOut)))
             {
-                Fail("failed envelopedData recode check");
+                pWrt.WriteObject(d);
             }
 
+            using (var pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))))
+            {
+                d = (ContentInfo)pemRd.ReadObject();
+
+                if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
+                {
+                    Fail("failed envelopedData recode check");
+                }
+            }
 
             // OpenSSL test cases (as embedded resources)
             doOpenSslDsaTest("unencrypted");
@@ -224,24 +227,27 @@ namespace Org.BouncyCastle.OpenSsl.Tests
 
             // encrypted private key test
             pGet = new Password("password".ToCharArray());
-            pemRd = OpenPemResource("enckey.pem", pGet);
-
-            RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject();
-
-            if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
+            using (var pemRd = OpenPemResource("enckey.pem", pGet))
             {
-                Fail("decryption of private key data check failed");
+                var privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject();
+
+                if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
+                {
+                    Fail("decryption of private key data check failed");
+                }
             }
 
             // general PKCS8 test
             pGet = new Password("password".ToCharArray());
-            pemRd = OpenPemResource("pkcs8test.pem", pGet);
-
-            while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null)
+            using (var pemRd = OpenPemResource("pkcs8test.pem", pGet))
             {
-                if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
+                RsaPrivateCrtKeyParameters privKey;
+                while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null)
                 {
-                    Fail("decryption of private key data check failed");
+                    if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
+                    {
+                        Fail("decryption of private key data check failed");
+                    }
                 }
             }
         }
@@ -251,36 +257,37 @@ namespace Org.BouncyCastle.OpenSsl.Tests
             AsymmetricCipherKeyPair	pair) 
         {
             MemoryStream bOut = new MemoryStream();
-            PemWriter pWrt = new PemWriter(new StreamWriter(bOut));
-
-            pWrt.WriteObject(pair.Public);
-            pWrt.Writer.Close();
-
-            PemReader pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
+            using (var pWrt = new PemWriter(new StreamWriter(bOut)))
+            {
+                pWrt.WriteObject(pair.Public);
+            }
 
-            AsymmetricKeyParameter pubK = (AsymmetricKeyParameter) pemRd.ReadObject();
-            if (!pubK.Equals(pair.Public))
+            using (var pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))))
             {
-                Fail("Failed public key read: " + name);
+                AsymmetricKeyParameter pubK = (AsymmetricKeyParameter)pemRd.ReadObject();
+                if (!pubK.Equals(pair.Public))
+                {
+                    Fail("Failed public key read: " + name);
+                }
             }
 
             bOut = new MemoryStream();
-            pWrt = new PemWriter(new StreamWriter(bOut));
-
-            pWrt.WriteObject(pair.Private);
-            pWrt.Writer.Close();
-
-            pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
-
-            AsymmetricCipherKeyPair kPair = (AsymmetricCipherKeyPair) pemRd.ReadObject();
-            if (!kPair.Private.Equals(pair.Private))
+            using (var pWrt = new PemWriter(new StreamWriter(bOut)))
             {
-                Fail("Failed private key read: " + name);
+                pWrt.WriteObject(pair.Private);
             }
-            
-            if (!kPair.Public.Equals(pair.Public))
+
+            using (var pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))))
             {
-                Fail("Failed private key public read: " + name);
+                AsymmetricCipherKeyPair kPair = (AsymmetricCipherKeyPair)pemRd.ReadObject();
+                if (!kPair.Private.Equals(pair.Private))
+                {
+                    Fail("Failed private key read: " + name);
+                }
+                if (!kPair.Public.Equals(pair.Public))
+                {
+                    Fail("Failed private key public read: " + name);
+                }
             }
         }
 
@@ -329,18 +336,19 @@ namespace Org.BouncyCastle.OpenSsl.Tests
             string	fileName,
             Type	expectedPrivKeyType)
         {
-            PemReader pr = OpenPemResource(fileName, new Password("changeit".ToCharArray()));
-            AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;
-            pr.Reader.Close();
-
-            if (kp == null)
+            using (var pr = OpenPemResource(fileName, new Password("changeit".ToCharArray())))
             {
-                Fail("Didn't find OpenSSL key");
-            }
+                AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;
 
-            if (!expectedPrivKeyType.IsInstanceOfType(kp.Private))
-            {
-                Fail("Returned key not of correct type");
+                if (kp == null)
+                {
+                    Fail("Didn't find OpenSSL key");
+                }
+
+                if (!expectedPrivKeyType.IsInstanceOfType(kp.Private))
+                {
+                    Fail("Returned key not of correct type");
+                }
             }
         }
 
@@ -351,13 +359,13 @@ namespace Org.BouncyCastle.OpenSsl.Tests
             try
             {
                 IPasswordFinder pGet = new Password(password.ToCharArray());
-                PemReader pemRd = OpenPemResource("test.pem", pGet);
-
-                object o;
-                while ((o = pemRd.ReadObject()) != null)
+                using (var pemRd = OpenPemResource("test.pem", pGet))
                 {
+                    object o;
+                    while ((o = pemRd.ReadObject()) != null)
+                    {
+                    }
                 }
-
                 Fail("issue not detected: " + index);
             }
             catch (Exception e)
diff --git a/crypto/test/src/openssl/test/WriterTest.cs b/crypto/test/src/openssl/test/WriterTest.cs
index 833a3d145..4bba4f5c6 100644
--- a/crypto/test/src/openssl/test/WriterTest.cs
+++ b/crypto/test/src/openssl/test/WriterTest.cs
@@ -106,13 +106,13 @@ namespace Org.BouncyCastle.OpenSsl.Tests
 			DoWriteReadTest(ecPriv);
 			DoWriteReadTests(ecPriv, algorithms);
 
-			// override test
-			PemWriter pWrt = new PemWriter(new StringWriter());
+            // override test
+            object o = new PemObject("FRED", new byte[100]);
 
-			object o = new PemObject("FRED", new byte[100]);
-			pWrt.WriteObject(o);
-
-			pWrt.Writer.Close();
+			using (var pWrt = new PemWriter(new StringWriter()))
+			{
+                pWrt.WriteObject(o);
+            }
 		}
 
 		private void DoWriteReadTests(
@@ -129,44 +129,46 @@ namespace Org.BouncyCastle.OpenSsl.Tests
 			AsymmetricKeyParameter	akp)
 		{
 			StringWriter sw = new StringWriter();
-			PemWriter pw = new PemWriter(sw);
-
-			pw.WriteObject(akp);
-			pw.Writer.Close();
+			using (var pw = new PemWriter(sw))
+			{
+                pw.WriteObject(akp);
+            }
 
 			string data = sw.ToString();
 
-			PemReader pr = new PemReader(new StringReader(data));
-
-			AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;
-
-			if (kp == null || !kp.Private.Equals(akp))
+			using (var pr = new PemReader(new StringReader(data)))
 			{
-				Fail("Failed to read back test key");
-			}
-		}
+                AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;
+
+                if (kp == null || !kp.Private.Equals(akp))
+                {
+                    Fail("Failed to read back test key");
+                }
+            }
+        }
 
 		private void DoWriteReadTest(
 			AsymmetricKeyParameter	akp,
 			string					algorithm)
 		{
 			StringWriter sw = new StringWriter();
-			PemWriter pw = new PemWriter(sw);
-
-			pw.WriteObject(akp, algorithm, testPassword, random);
-			pw.Writer.Close();
+			using (var pw = new PemWriter(sw))
+			{
+                pw.WriteObject(akp, algorithm, testPassword, random);
+            }
 
 			string data = sw.ToString();
 
-			PemReader pr = new PemReader(new StringReader(data), new Password(testPassword));
-
-			AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;
-
-			if (kp == null || !kp.Private.Equals(akp))
+			using (var pr = new PemReader(new StringReader(data), new Password(testPassword)))
 			{
-				Fail("Failed to read back test key encoded with: " + algorithm);
-			}
-		}
+                AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;
+
+                if (kp == null || !kp.Private.Equals(akp))
+                {
+                    Fail("Failed to read back test key encoded with: " + algorithm);
+                }
+            }
+        }
 
 		[Test]
 		public void TestFunction()
diff --git a/crypto/test/src/test/rsa3/RSA3CertTest.cs b/crypto/test/src/test/rsa3/RSA3CertTest.cs
index 913f4f015..5c0bdb321 100644
--- a/crypto/test/src/test/rsa3/RSA3CertTest.cs
+++ b/crypto/test/src/test/rsa3/RSA3CertTest.cs
@@ -103,10 +103,11 @@ namespace Org.BouncyCastle.Tests.Rsa3
 		{
 			Stream s = SimpleTest.GetTestDataAsStream("rsa3." + certName);
 			TextReader tr = new StreamReader(s);
-			PemReader rd = new PemReader(tr);
-
-			return (X509Certificate) rd.ReadObject();
-		}
+			using (var rd = new PemReader(tr))
+			{
+                return (X509Certificate)rd.ReadObject();
+            }
+        }
 
 //		public static void main (string[] args) 
 //			throws Exception
diff --git a/crypto/test/src/tls/test/TlsTestUtilities.cs b/crypto/test/src/tls/test/TlsTestUtilities.cs
index a3526ab6b..3baf233c7 100644
--- a/crypto/test/src/tls/test/TlsTestUtilities.cs
+++ b/crypto/test/src/tls/test/TlsTestUtilities.cs
@@ -371,13 +371,12 @@ namespace Org.BouncyCastle.Tls.Tests
         }
 
         internal static PemObject LoadPemResource(string resource)
-           
         {
             Stream s = SimpleTest.GetTestDataAsStream("tls." + resource);
-            PemReader p = new PemReader(new StreamReader(s));
-            PemObject o = p.ReadPemObject();
-            p.Reader.Close();
-            return o;
+            using (var p = new PemReader(new StreamReader(s)))
+            {
+                return p.ReadPemObject();
+            }
         }
 
         internal static bool AreSameCertificate(TlsCrypto crypto, TlsCertificate cert, string resource)
diff --git a/crypto/test/src/util/io/pem/test/AllTests.cs b/crypto/test/src/util/io/pem/test/AllTests.cs
index 88ccf2e40..55357c77a 100644
--- a/crypto/test/src/util/io/pem/test/AllTests.cs
+++ b/crypto/test/src/util/io/pem/test/AllTests.cs
@@ -38,9 +38,11 @@ namespace Org.BouncyCastle.Utilities.IO.Pem.Tests
         {
 			try
 			{
-				PemReader rd = new PemReader(new StringReader("-----BEGIN \n"));
-				rd.ReadPemObject();
-				Assert.Fail("must fail on malformed");
+				using (var rd = new PemReader(new StringReader("-----BEGIN \n")))
+				{
+                    rd.ReadPemObject();
+                }
+                Assert.Fail("must fail on malformed");
 			}
 			catch (IOException ioex)
             {
@@ -50,14 +52,15 @@ namespace Org.BouncyCastle.Utilities.IO.Pem.Tests
 
 		private void LengthTest(string type, IList<PemHeader> headers, byte[] data)
 		{
-			StringWriter sw = new StringWriter();
-			PemWriter pWrt = new PemWriter(sw);
+            PemObject pemObj = new PemObject(type, headers, data);
 
-			PemObject pemObj = new PemObject(type, headers, data);
-			pWrt.WriteObject(pemObj);
-			pWrt.Writer.Close();
+            StringWriter sw = new StringWriter();
 
-			Assert.AreEqual(sw.ToString().Length, pWrt.GetOutputSize(pemObj));
-		}
+			using (var pWrt = new PemWriter(sw))
+			{
+                pWrt.WriteObject(pemObj);
+                Assert.AreEqual(sw.ToString().Length, pWrt.GetOutputSize(pemObj));
+            }
+        }
 	}
 }