>From 48fe45e75eaa46358caac5d23b5373a359e023cc Mon Sep 17 00:00:00 2001
From: Ade Lee <alee@redhat.com>
Date: Fri, 8 Mar 2013 09:29:02 -0500
Subject: [PATCH] Plug resource leaks

---
 .../src/com/netscape/ca/CertificateAuthority.java  |   9 +-
 .../netscape/certsrv/authentication/AuthToken.java |  11 +-
 .../src/com/netscape/cms/logging/LogFile.java      |  21 ++-
 .../netscape/cms/profile/def/EnrollDefault.java    |   3 +-
 .../cms/profile/def/GenericExtDefault.java         |   3 +-
 .../netscape/cms/servlet/common/CMSTemplate.java   |   9 +-
 .../netscape/cms/servlet/csadmin/GetCookie.java    |   3 -
 .../com/netscape/cmscore/base/PropConfigStore.java |   6 +-
 .../com/netscape/cmscore/security/KeyCertUtil.java |  45 ++---
 .../com/netscape/cmscore/security/PWsdrCache.java  |  20 +--
 .../netscape/cmscore/util/ExceptionFormatter.java  |   7 +-
 .../certsrv/authentication/AuthTokenTest.java      |   9 +-
 .../java-tools/src/com/netscape/cmstools/BtoA.java |   4 +
 .../src/com/netscape/cmstools/DRMTool.java         |   4 +-
 .../src/com/netscape/cmstools/ExtJoiner.java       |   3 +-
 .../src/com/netscape/cmstools/GenExtKeyUsage.java  |  11 +-
 .../src/com/netscape/cmstools/PKCS10Client.java    |   2 +-
 .../src/com/netscape/cmstools/PasswordCache.java   |  20 +--
 base/kra/src/com/netscape/kra/EncryptionUnit.java  |   6 +-
 .../src/com/netscape/kra/NetkeyKeygenService.java  |  28 +--
 .../com/netscape/kra/TokenKeyRecoveryService.java  |  20 +--
 base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java |   3 +-
 .../com/netscape/cmsutil/crypto/CryptoUtil.java    |  29 +--
 .../security/extensions/AccessDescription.java     |  15 +-
 .../extensions/AuthInfoAccessExtension.java        |  23 +--
 .../CertificateRenewalWindowExtension.java         |  17 +-
 .../extensions/CertificateScopeOfUseExtension.java |  23 +--
 .../extensions/InhibitAnyPolicyExtension.java      |  27 +--
 .../netscape/security/extensions/KerberosName.java |  53 +++---
 .../security/extensions/NSCertTypeExtension.java   |   9 +-
 .../extensions/PresenceServerExtension.java        |  29 +--
 .../extensions/SubjectInfoAccessExtension.java     |  23 +--
 .../netscape/security/pkcs/PKCS10Attribute.java    |  33 ++--
 .../netscape/security/pkcs/PKCS10Attributes.java   |  18 +-
 .../src/netscape/security/pkcs/PKCS9Attribute.java | 200 ++++++++++-----------
 .../netscape/security/pkcs/PKCS9Attributes.java    |  13 +-
 .../src/netscape/security/pkcs/SignerInfo.java     |  39 ++--
 base/util/src/netscape/security/provider/DSA.java  |   3 +-
 .../netscape/security/provider/DSAParameters.java  |  17 +-
 .../netscape/security/provider/RSAPublicKey.java   |   4 +-
 base/util/src/netscape/security/x509/AVA.java      |  15 +-
 base/util/src/netscape/security/x509/AlgIdDSA.java |  14 +-
 .../src/netscape/security/x509/AlgorithmId.java    |  43 +++--
 .../util/src/netscape/security/x509/Attribute.java |  52 +++---
 .../x509/AuthorityKeyIdentifierExtension.java      |  48 ++---
 .../security/x509/BasicConstraintsExtension.java   |  21 ++-
 .../netscape/security/x509/CRLNumberExtension.java |   9 +-
 .../netscape/security/x509/CRLReasonExtension.java |   9 +-
 .../security/x509/CertificateExtensions.java       |  39 ++--
 .../x509/CertificatePoliciesExtension.java         |  15 +-
 .../security/x509/CertificateValidity.java         |  31 ++--
 .../netscape/security/x509/CertificateVersion.java |  15 +-
 .../security/x509/DeltaCRLIndicatorExtension.java  |   9 +-
 .../util/src/netscape/security/x509/Extension.java |   3 +-
 .../src/netscape/security/x509/Extensions.java     |   9 +-
 .../security/x509/HoldInstructionExtension.java    |  10 +-
 .../security/x509/InvalidityDateExtension.java     |   9 +-
 .../netscape/security/x509/KeyUsageExtension.java  |   9 +-
 .../security/x509/NSCCommentExtension.java         |  14 +-
 .../security/x509/NameConstraintsExtension.java    |  41 +++--
 .../security/x509/PolicyConstraintsExtension.java  |  33 ++--
 .../security/x509/PolicyMappingsExtension.java     |  15 +-
 .../security/x509/PrivateKeyUsageExtension.java    |  33 ++--
 .../netscape/security/x509/RevokedCertImpl.java    |   6 +-
 .../x509/SubjectDirAttributesExtension.java        |  23 +--
 base/util/src/netscape/security/x509/X500Name.java |  28 +--
 .../src/netscape/security/x509/X509CRLImpl.java    |  10 +-
 base/util/src/netscape/security/x509/X509Cert.java |  33 ++--
 .../src/netscape/security/x509/X509CertImpl.java   |   3 +-
 .../com/netscape/security/util/StringTestUtil.java |  36 ++--
 70 files changed, 777 insertions(+), 680 deletions(-)

diff --git a/base/ca/src/com/netscape/ca/CertificateAuthority.java b/base/ca/src/com/netscape/ca/CertificateAuthority.java
index 50ef503b66939e7e40b57f535dc3b7c4da9d3ca2..91f41ebad7eb3227e7dbd160b593275d64551faa 100644
--- a/base/ca/src/com/netscape/ca/CertificateAuthority.java
+++ b/base/ca/src/com/netscape/ca/CertificateAuthority.java
@@ -960,8 +960,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
             statsSub.startTiming("signing");
         }
 
-        try {
-            DerOutputStream out = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()) {
             DerOutputStream tmp = new DerOutputStream();
 
             if (algname == null) {
@@ -1034,8 +1033,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
             statsSub.startTiming("signing");
         }
 
-        try {
-            DerOutputStream out = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()){
             DerOutputStream tmp = new DerOutputStream();
 
             if (certInfo == null) {
@@ -1931,8 +1929,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
     }
 
     private BasicOCSPResponse sign(ResponseData rd) throws EBaseException {
-        try {
-            DerOutputStream out = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()){
             DerOutputStream tmp = new DerOutputStream();
 
             String algname = mOCSPSigningUnit.getDefaultAlgorithm();
diff --git a/base/common/src/com/netscape/certsrv/authentication/AuthToken.java b/base/common/src/com/netscape/certsrv/authentication/AuthToken.java
index 827278711aff430373ca36c014c2e0550766e68b..18e34998dbcc4c714c71ad3e0de733a9b2d69a2c 100644
--- a/base/common/src/com/netscape/certsrv/authentication/AuthToken.java
+++ b/base/common/src/com/netscape/certsrv/authentication/AuthToken.java
@@ -257,9 +257,9 @@ public class AuthToken implements IAuthToken {
         if (value == null) {
             return false;
         }
-        DerOutputStream out = new DerOutputStream();
+
         DerValue[] derValues = new DerValue[value.length];
-        try {
+        try (DerOutputStream out = new DerOutputStream()){
             for (int i = 0; i < value.length; i++) {
                 derValues[i] = new DerValue(value[i]);
             }
@@ -343,10 +343,9 @@ public class AuthToken implements IAuthToken {
         if (value == null) {
             return false;
         }
-        DerOutputStream derStream = new DerOutputStream();
         X509Certificate[] certArray = value.getCertificates();
         DerValue[] derValues = new DerValue[certArray.length];
-        try {
+        try (DerOutputStream derStream = new DerOutputStream()){
             for (int i = 0; i < certArray.length; i++) {
                 ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
                 try {
@@ -386,9 +385,9 @@ public class AuthToken implements IAuthToken {
         if (value == null) {
             return false;
         }
-        DerOutputStream out = new DerOutputStream();
+
         DerValue[] derValues = new DerValue[value.length];
-        try {
+        try (DerOutputStream out = new DerOutputStream()){
             for (int i = 0; i < value.length; i++) {
                 derValues[i] = new DerValue(DerValue.tag_OctetString, value[i]);
             }
diff --git a/base/common/src/com/netscape/cms/logging/LogFile.java b/base/common/src/com/netscape/cms/logging/LogFile.java
index caada0bf5177f147a329550b5c45f1540a90427e..91ba709aab2df3dafbcd91f77f32d8a129613971 100644
--- a/base/common/src/com/netscape/cms/logging/LogFile.java
+++ b/base/common/src/com/netscape/cms/logging/LogFile.java
@@ -343,18 +343,17 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
         // All this streaming is lame, but Base64OutputStream needs a
         // PrintStream
         ByteArrayOutputStream output = new ByteArrayOutputStream();
-        Base64OutputStream b64 = new Base64OutputStream(new
-                PrintStream(new
-                        FilterOutputStream(output)
-                )
-                );
+        try (Base64OutputStream b64 = new Base64OutputStream(
+                new PrintStream(new FilterOutputStream(output)))) {
+            b64.write(bytes);
+            b64.flush();
 
-        b64.write(bytes);
-        b64.flush();
-
-        // This is internationally safe because Base64 chars are
-        // contained within 8859_1
-        return output.toString("8859_1");
+            // This is internationally safe because Base64 chars are
+            // contained within 8859_1
+            return output.toString("8859_1");
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     private static boolean mInSignedAuditLogFailureMode = false;
diff --git a/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java b/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java
index 53ec23b404d64a6b8525352b91fa2149a1c02ac9..7b4c3c74dfd78f747e64e79f06b92cc0fa10b69f 100644
--- a/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java
+++ b/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java
@@ -620,8 +620,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
 
         // if the OID isn't valid (ex. n.n) the error isn't caught til
         // encoding time leaving a bad request in the request queue.
-        try {
-            DerOutputStream derOut = new DerOutputStream();
+        try (DerOutputStream derOut = new DerOutputStream()) {
 
             derOut.putOID(v);
             new ObjectIdentifier(new DerInputStream(derOut.toByteArray()));
diff --git a/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java b/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java
index 4a8acace1945009404a0286919750ac99e18b4c2..f344648abb258062d73f627b9136eeb09013769d 100644
--- a/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java
+++ b/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java
@@ -230,7 +230,7 @@ public class GenericExtDefault extends EnrollExtDefault {
     public Extension createExtension(IRequest request) {
         Extension ext = null;
 
-        try {
+        try (DerOutputStream out = new DerOutputStream()) {
             boolean critical = getConfigBoolean(CONFIG_CRITICAL);
             ObjectIdentifier oid = new ObjectIdentifier(getConfig(CONFIG_OID));
             byte data[] = null;
@@ -241,7 +241,6 @@ public class GenericExtDefault extends EnrollExtDefault {
                 data = getBytes(mapPattern(request, getConfig(CONFIG_DATA)));
             }
 
-            DerOutputStream out = new DerOutputStream();
             out.putOctetString(data);
 
             ext = new Extension(oid, critical, out.toByteArray());
diff --git a/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java b/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java
index 0188b781ae228bf121a94088a75b5691ca501f86..336032dd39c3c92380cd5b39d531b3c0f17048cb 100644
--- a/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java
+++ b/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java
@@ -145,14 +145,9 @@ public class CMSTemplate extends CMSFile {
         Enumeration<IArgBlock> q = null;
         IArgBlock r = null;
         CMSTemplateParams data = input;
-        HTTPOutputStreamWriter http_out = null;
 
-        if (mCharset == null)
-            http_out = new HTTPOutputStreamWriter(rout);
-        else
-            http_out = new HTTPOutputStreamWriter(rout, mCharset);
-
-        try {
+        try (HTTPOutputStreamWriter http_out = (mCharset == null ?
+                new HTTPOutputStreamWriter(rout): new HTTPOutputStreamWriter(rout, mCharset))) {
             templateLine out = new templateLine();
 
             // Output the prolog
diff --git a/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java b/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java
index 6e269089e4efa0741d249859164118c2caf5ed28..78d8dab6ba170405266fa96de61b17267e805464 100644
--- a/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java
+++ b/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java
@@ -21,7 +21,6 @@ import java.io.IOException;
 import java.net.URL;
 import java.net.URLDecoder;
 import java.util.Locale;
-import java.util.Random;
 
 import javax.servlet.ServletConfig;
 import javax.servlet.ServletException;
@@ -49,7 +48,6 @@ public class GetCookie extends CMSServlet {
      *
      */
     private static final long serialVersionUID = 2466968231929541707L;
-    private static Random mRandom = null;
     private String mErrorFormPath = null;
     private String mFormPath = null;
 
@@ -72,7 +70,6 @@ public class GetCookie extends CMSServlet {
 
         CMS.debug("GetCookie init");
         mTemplates.remove(CMSRequest.SUCCESS);
-        mRandom = new Random();
         mErrorFormPath = sc.getInitParameter("errorTemplatePath");
         if (mOutputTemplatePath != null) {
             mFormPath = mOutputTemplatePath;
diff --git a/base/common/src/com/netscape/cmscore/base/PropConfigStore.java b/base/common/src/com/netscape/cmscore/base/PropConfigStore.java
index 075d4be78f48f07f1982a5ed0fb72dca20a18f78..161f549f2148c35bcbf9e985f079394ff545984a 100644
--- a/base/common/src/com/netscape/cmscore/base/PropConfigStore.java
+++ b/base/common/src/com/netscape/cmscore/base/PropConfigStore.java
@@ -355,10 +355,8 @@ public class PropConfigStore implements IConfigStore, Cloneable {
      */
     public void putByteArray(String name, byte value[]) {
         ByteArrayOutputStream output = new ByteArrayOutputStream();
-        Base64OutputStream b64 = new Base64OutputStream(new
-                PrintStream(new FilterOutputStream(output)));
-
-        try {
+        try (Base64OutputStream b64 = new Base64OutputStream(new
+                PrintStream(new FilterOutputStream(output)))) {
             b64.write(value);
             b64.flush();
 
diff --git a/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java b/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java
index 210c042276b937a40bc206dce72f670834c1e8e0..9ccdc6f595ac92f925305811348b436caa369ccd 100644
--- a/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java
+++ b/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java
@@ -175,36 +175,38 @@ public class KeyCertUtil {
         // All this streaming is lame, but Base64OutputStream needs a
         // PrintStream
         ByteArrayOutputStream output = new ByteArrayOutputStream();
-        Base64OutputStream b64 = new Base64OutputStream(new
-                PrintStream(new
-                        FilterOutputStream(output)
-                )
-                );
+        try (Base64OutputStream b64 = new Base64OutputStream(
+                new PrintStream(new FilterOutputStream(output)))) {
 
-        b64.write(bytes);
-        b64.flush();
+            b64.write(bytes);
+            b64.flush();
 
-        // This is internationally safe because Base64 chars are
-        // contained within 8859_1
-        return output.toString("8859_1");
+            // This is internationally safe because Base64 chars are
+            // contained within 8859_1
+            return output.toString("8859_1");
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     public static byte[] makeDSSParms(BigInteger P, BigInteger Q, BigInteger G)
             throws IOException {
+        try (DerOutputStream sequence = new DerOutputStream()) {
 
-        // Write P, Q, G to a DER stream
-        DerOutputStream contents = new DerOutputStream();
+            // Write P, Q, G to a DER stream
+            DerOutputStream contents = new DerOutputStream();
 
-        contents.putInteger(new BigInt(P));
-        contents.putInteger(new BigInt(Q));
-        contents.putInteger(new BigInt(G));
+            contents.putInteger(new BigInt(P));
+            contents.putInteger(new BigInt(Q));
+            contents.putInteger(new BigInt(G));
 
-        // Make a sequence from the PQG stream
-        DerOutputStream sequence = new DerOutputStream();
+            // Make a sequence from the PQG stream
+            sequence.write(DerValue.tag_Sequence, contents);
 
-        sequence.write(DerValue.tag_Sequence, contents);
-
-        return sequence.toByteArray();
+            return sequence.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     public static PrivateKey getPrivateKey(String tokenname, String nickname)
@@ -235,7 +237,7 @@ public class KeyCertUtil {
     public static X509CertImpl signCert(PrivateKey privateKey, X509CertInfo certInfo,
             SignatureAlgorithm sigAlg)
             throws NoSuchTokenException, EBaseException, NotInitializedException {
-        try {
+        try (DerOutputStream out = new DerOutputStream()) {
             CertificateAlgorithmId sId = (CertificateAlgorithmId)
                     certInfo.get(X509CertInfo.ALGORITHM_ID);
             AlgorithmId sigAlgId =
@@ -246,7 +248,6 @@ public class KeyCertUtil {
             CryptoToken token = priKey.getOwningToken();
 
             DerOutputStream tmp = new DerOutputStream();
-            DerOutputStream out = new DerOutputStream();
 
             certInfo.encode(tmp);
 
diff --git a/base/common/src/com/netscape/cmscore/security/PWsdrCache.java b/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
index d723d55ed775c16632692cef5e452dc794beaaf4..bec09cdb6a4da52e7e6326e9f82dbaf71e8a0dd7 100644
--- a/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
+++ b/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
@@ -191,18 +191,18 @@ public class PWsdrCache {
         // All this streaming is lame, but Base64OutputStream needs a
         // PrintStream
         ByteArrayOutputStream output = new ByteArrayOutputStream();
-        Base64OutputStream b64 = new Base64OutputStream(new
-                PrintStream(new
-                        FilterOutputStream(output)
-                )
-                );
+        try (Base64OutputStream b64 = new Base64OutputStream(
+                new PrintStream(new FilterOutputStream(output)))) {
 
-        b64.write(bytes);
-        b64.flush();
+            b64.write(bytes);
+            b64.flush();
 
-        // This is internationally safe because Base64 chars are
-        // contained within 8859_1
-        return output.toString("8859_1");
+            // This is internationally safe because Base64 chars are
+            // contained within 8859_1
+            return output.toString("8859_1");
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     // for PWCBsdr
diff --git a/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java b/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java
index 88dd32a051d367ec67e72cf627a0ed6cc12f5f26..14351cd7b91cabb59a13e92617b6f55832895ac8 100644
--- a/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java
+++ b/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java
@@ -35,12 +35,10 @@ public class ExceptionFormatter {
     public static String getStackTraceAsString(Throwable e) {
         String returnvalue = e.toString();
 
-        try {
-            PipedOutputStream po = new PipedOutputStream();
-            PipedInputStream pi = new PipedInputStream(po);
+        PipedOutputStream po = new PipedOutputStream();
+        try (PipedInputStream pi = new PipedInputStream(po)) {
 
             PrintWriter ps = new PrintWriter(po);
-
             e.printStackTrace(ps);
             ps.flush();
 
@@ -52,7 +50,6 @@ public class ExceptionFormatter {
         } catch (Exception ex) {
         }
         return returnvalue;
-
     }
 
     /* test code below */
diff --git a/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java b/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java
index 1a5d999f6e57f003a55c21f871a3111379504a04..c4440456eb78fae9a99ea9821e44ade491bce6a7 100644
--- a/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java
+++ b/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java
@@ -154,9 +154,12 @@ public class AuthTokenTest extends CMSBaseTestCase {
         authToken.set("key2", new byte[] { 1, 2, 3, 4 });
         assertNull(authToken.getInStringArray("key2"));
 
-        DerOutputStream out = new DerOutputStream();
-        out.putPrintableString("testing");
-        authToken.set("key3", out.toByteArray());
+        try (DerOutputStream out = new DerOutputStream()) {
+            out.putPrintableString("testing");
+            authToken.set("key3", out.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
         assertNull(authToken.getInStringArray("key3"));
 
         assertFalse(authToken.set("key4", (String[]) null));
diff --git a/base/java-tools/src/com/netscape/cmstools/BtoA.java b/base/java-tools/src/com/netscape/cmstools/BtoA.java
index 8c240dac6159a52b97e1e7e15b2d8a6152b7a2cb..ac4e3894285b8817d85cc59f39a8f57cc9eff2da 100644
--- a/base/java-tools/src/com/netscape/cmstools/BtoA.java
+++ b/base/java-tools/src/com/netscape/cmstools/BtoA.java
@@ -82,6 +82,10 @@ public class BtoA {
         } catch (IOException e) {
             System.out.println("BtoA():  unable to open file " +
                     argv[1] + " for writing:\n" + e);
+            try {
+                inputBlob.close();
+            } catch (IOException e1) {
+            }
             return;
         }
 
diff --git a/base/java-tools/src/com/netscape/cmstools/DRMTool.java b/base/java-tools/src/com/netscape/cmstools/DRMTool.java
index 4403dc8ecf62b63c382abefb688f88ab94fd1c45..55d1eddd1f91921c23f3bab9e73e6d20ffd2daae 100644
--- a/base/java-tools/src/com/netscape/cmstools/DRMTool.java
+++ b/base/java-tools/src/com/netscape/cmstools/DRMTool.java
@@ -1828,7 +1828,6 @@ public class DRMTool {
         KeyWrapper target_rsaWrap = null;
         byte target_session[] = null;
         DerOutputStream tmp = null;
-        DerOutputStream out = null;
         byte[] rewrappedKeyData = null;
 
         // public byte[]
@@ -1909,7 +1908,7 @@ public class DRMTool {
         // public byte[]
         // mStorageUnit.encryptInternalPrivate( byte priKey[] )
         // throws EBaseException
-        try {
+        try (DerOutputStream out = new DerOutputStream()){
             // Use "mSourceToken" to get "KeyWrapAlgorithm.RSA"
             target_rsaWrap = mSourceToken.getKeyWrapper(
                                  KeyWrapAlgorithm.RSA);
@@ -1917,7 +1916,6 @@ public class DRMTool {
             target_session = target_rsaWrap.wrap(sk);
 
             tmp = new DerOutputStream();
-            out = new DerOutputStream();
 
             tmp.putOctetString(target_session);
             tmp.putOctetString(pri);
diff --git a/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java b/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
index 5aac69e60755ad96aa09420fe2871b217937af56..fed33d2dd809341cb6910ac1e99213d8e7168a77 100644
--- a/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
+++ b/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
@@ -68,7 +68,7 @@ import com.netscape.cmsutil.util.Utils;
 public class ExtJoiner {
 
     public static void main(String args[]) {
-        try {
+        try (DerOutputStream out = new DerOutputStream()) {
             if (args.length == 0) {
                 System.out.println("Usage:  ExtJoiner <ext_file0> <ext_file1> ... <ext_fileN>");
                 System.exit(0);
@@ -80,7 +80,6 @@ public class ExtJoiner {
 
                 exts[i] = new DerValue(data);
             }
-            DerOutputStream out = new DerOutputStream();
 
             out.putSequence(exts);
             System.out.println(Utils.base64encode(out.toByteArray()));
diff --git a/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java b/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java
index 9476d3ee4d582d9bcf7cbc26a904a46931f6b19b..5eb429feba6bec034f266c9a71ec0558ae7cbd11 100644
--- a/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java
+++ b/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java
@@ -19,13 +19,13 @@ package com.netscape.cmstools;
 
 import java.util.Vector;
 
-import com.netscape.cmsutil.util.Utils;
-
 import netscape.security.util.DerOutputStream;
 import netscape.security.util.DerValue;
 import netscape.security.util.ObjectIdentifier;
 import netscape.security.x509.Extension;
 
+import com.netscape.cmsutil.util.Utils;
+
 /**
  * Generates a DER-encoded Extended Key Usage extension.
  * The first parameter is the criticality of the extension, true or false.
@@ -38,7 +38,8 @@ import netscape.security.x509.Extension;
 public class GenExtKeyUsage {
 
     public static void main(String[] args) {
-        try {
+        try (DerOutputStream seq = new DerOutputStream();
+             DerOutputStream octetString = new DerOutputStream()){
             if (args.length < 2) {
                 System.out.println("Usage:  GenExtKeyUsage [true|false] <OID> ...");
                 System.exit(-1);
@@ -72,13 +73,9 @@ public class GenExtKeyUsage {
             }
 
             // stuff the object identifiers into a SEQUENCE
-            DerOutputStream seq = new DerOutputStream();
-
             seq.write(DerValue.tag_Sequence, contents);
 
             // encode the SEQUENCE in an octet string
-            DerOutputStream octetString = new DerOutputStream();
-
             octetString.putOctetString(seq.toByteArray());
 
             // Construct an extension
diff --git a/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java b/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java
index a138ae29d661033d747272272ff56fa2183e8112..f3eac9ff4837aae9e352d68431d6aabe293696ba 100644
--- a/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java
+++ b/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java
@@ -88,7 +88,7 @@ public class PKCS10Client {
     }
 
     public static void main(String args[]) throws Exception {
-        String dbdir = null, ofilename = null, password = null, subjectName = null, type = null, tokenName = null;
+        String dbdir = null, ofilename = null, password = null, subjectName = null, tokenName = null;
 
         String alg = "rsa";
         String ecc_curve = "nistp256";
diff --git a/base/java-tools/src/com/netscape/cmstools/PasswordCache.java b/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
index d97a21706aa4e486437fded22a3b90dfaab0b3d6..1a451cdec8d60d3a70683f1dc1e0883aadcf34e8 100644
--- a/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
+++ b/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
@@ -127,18 +127,18 @@ public class PasswordCache {
         // All this streaming is lame, but Base64OutputStream needs a
         // PrintStream
         ByteArrayOutputStream output = new ByteArrayOutputStream();
-        Base64OutputStream b64 = new Base64OutputStream(new
-                PrintStream(new
-                        FilterOutputStream(output)
-                )
-                );
+        try (Base64OutputStream b64 = new Base64OutputStream(
+                new PrintStream(new FilterOutputStream(output)))) {
 
-        b64.write(bytes);
-        b64.flush();
+            b64.write(bytes);
+            b64.flush();
 
-        // This is internationally safe because Base64 chars are
-        // contained within 8859_1
-        return output.toString("8859_1");
+            // This is internationally safe because Base64 chars are
+            // contained within 8859_1
+            return output.toString("8859_1");
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     public static void main(String[] av) {
diff --git a/base/kra/src/com/netscape/kra/EncryptionUnit.java b/base/kra/src/com/netscape/kra/EncryptionUnit.java
index c6023e6c55a1887635ed22c24e55119ecb23d1b1..78f6e2719383385551d5fd679acbf424ba5f849b 100644
--- a/base/kra/src/com/netscape/kra/EncryptionUnit.java
+++ b/base/kra/src/com/netscape/kra/EncryptionUnit.java
@@ -82,7 +82,7 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
      */
     public byte[] encryptInternalPrivate(byte priKey[])
             throws EBaseException {
-        try {
+        try (DerOutputStream out = new DerOutputStream()) {
             CMS.debug("EncryptionUnit.encryptInternalPrivate");
             CryptoToken internalToken = getInternalToken();
 
@@ -112,7 +112,6 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
             // }
 
             DerOutputStream tmp = new DerOutputStream();
-            DerOutputStream out = new DerOutputStream();
 
             tmp.putOctetString(session);
             tmp.putOctetString(pri);
@@ -641,7 +640,7 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
      * Internal wrap, accounts for either private or symmetric key
      */
     private byte[] _wrap(PrivateKey priKey, SymmetricKey symmKey) throws EBaseException {
-        try {
+        try (DerOutputStream out = new DerOutputStream()) {
             if ((priKey == null && symmKey == null) || (priKey != null && symmKey != null)) {
                 return null;
             }
@@ -691,7 +690,6 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
             // }
 
             DerOutputStream tmp = new DerOutputStream();
-            DerOutputStream out = new DerOutputStream();
 
             tmp.putOctetString(session);
             tmp.putOctetString(pri);
diff --git a/base/kra/src/com/netscape/kra/NetkeyKeygenService.java b/base/kra/src/com/netscape/kra/NetkeyKeygenService.java
index 3acea9ae11300c1e63cf6a93b9a79c2d71fdeb5a..da0db1a6a6702b4f5a2236c1ec6d72b3cf30cad6 100644
--- a/base/kra/src/com/netscape/kra/NetkeyKeygenService.java
+++ b/base/kra/src/com/netscape/kra/NetkeyKeygenService.java
@@ -176,7 +176,7 @@ public class NetkeyKeygenService implements IService {
                         tp = true;
                         sp = false;
                         ep = true;
-                    } else   
+                    } else
                         tp = true;
                     }
             } catch (Exception e) {
@@ -270,7 +270,7 @@ public class NetkeyKeygenService implements IService {
                     // 602548 NSS bug - to overcome it, we use isBadDSAKeyPair
                     kp = kpGen.genKeyPair();
                 }
-                while (isBadDSAKeyPair(kp)); 
+                while (isBadDSAKeyPair(kp));
                 */
                 return kp;
             }
@@ -312,18 +312,18 @@ public class NetkeyKeygenService implements IService {
         // All this streaming is lame, but Base64OutputStream needs a
         // PrintStream
         ByteArrayOutputStream output = new ByteArrayOutputStream();
-        Base64OutputStream b64 = new Base64OutputStream(new
-                PrintStream(new
-                        FilterOutputStream(output)
-                )
-                );
+        try (Base64OutputStream b64 = new Base64OutputStream(
+                new PrintStream(new FilterOutputStream(output)))) {
 
-        b64.write(bytes);
-        b64.flush();
+            b64.write(bytes);
+            b64.flush();
 
-        // This is internationally safe because Base64 chars are
-        // contained within 8859_1
-        return output.toString("8859_1");
+            // This is internationally safe because Base64 chars are
+            // contained within 8859_1
+            return output.toString("8859_1");
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     // this encrypts bytes with a symmetric key
@@ -443,7 +443,7 @@ public class NetkeyKeygenService implements IService {
             CMS.debug("NetkeyKeygenService: failed getting keygenToken");
             request.setExtData(IRequest.RESULT, Integer.valueOf(10));
             return false;
-        } else 
+        } else
             CMS.debug("NetkeyKeygenService: got keygenToken");
 
         if ((wrapped_des_key != null) &&
@@ -659,7 +659,7 @@ public class NetkeyKeygenService implements IService {
                             oidDescription);
 
                         rec.set(IKeyRecord.ATTR_META_INFO, metaInfo);
-                        // key size does not apply to EC; 
+                        // key size does not apply to EC;
                         rec.setKeySize(-1);
                     }
 
diff --git a/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java b/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java
index 6ce8d11a44fa197a24f14714947ea179a9ed0bee..c7228e2f9217e2f5568adad727d05a16dc2eba3b 100644
--- a/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java
+++ b/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java
@@ -154,18 +154,18 @@ public class TokenKeyRecoveryService implements IService {
         // All this streaming is lame, but Base64OutputStream needs a
         // PrintStream
         ByteArrayOutputStream output = new ByteArrayOutputStream();
-        Base64OutputStream b64 = new Base64OutputStream(new
-                PrintStream(new
-                        FilterOutputStream(output)
-                )
-                );
+        try (Base64OutputStream b64 = new Base64OutputStream(
+                new PrintStream(new FilterOutputStream(output)))) {
 
-        b64.write(bytes);
-        b64.flush();
+            b64.write(bytes);
+            b64.flush();
 
-        // This is internationally safe because Base64 chars are
-        // contained within 8859_1
-        return output.toString("8859_1");
+            // This is internationally safe because Base64 chars are
+            // contained within 8859_1
+            return output.toString("8859_1");
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     // this encrypts bytes with a symmetric key
diff --git a/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java b/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java
index 836907dac66c52f6f539c57585e9daadf7e0812b..eb9060663c0ff5336cf7d4d0736b6d6284d2ae49 100644
--- a/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java
+++ b/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java
@@ -429,8 +429,7 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
      */
     public BasicOCSPResponse sign(ResponseData rd)
             throws EBaseException {
-        try {
-            DerOutputStream out = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()) {
             DerOutputStream tmp = new DerOutputStream();
 
             String algname = mSigningUnit.getDefaultAlgorithm();
diff --git a/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java b/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java
index 81378ac1a428f71c4d1cf1bef1d098092f2c089c..b173055256b729954394e673ecfc929cde2f7965 100644
--- a/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java
+++ b/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java
@@ -379,16 +379,18 @@ public class CryptoUtil {
         // All this streaming is lame, but Base64OutputStream needs a
         // PrintStream
         ByteArrayOutputStream output = new ByteArrayOutputStream();
-        Base64OutputStream b64 = new Base64OutputStream(new
-                PrintStream(new
-                        FilterOutputStream(output)));
+        try (Base64OutputStream b64 = new Base64OutputStream(
+                new PrintStream(new FilterOutputStream(output)))) {
 
-        b64.write(bytes);
-        b64.flush();
+            b64.write(bytes);
+            b64.flush();
 
-        // This is internationally safe because Base64 chars are
-        // contained within 8859_1
-        return output.toString("8859_1");
+            // This is internationally safe because Base64 chars are
+            // contained within 8859_1
+            return output.toString("8859_1");
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     public static byte[] base64Decode(String s) throws IOException {
@@ -824,7 +826,6 @@ public class CryptoUtil {
         CryptoToken token = priKey.getOwningToken();
 
         DerOutputStream tmp = new DerOutputStream();
-        DerOutputStream out = new DerOutputStream();
 
         certInfo.encode(tmp);
         Signature signer = token.getSignatureContext(sigAlg);
@@ -835,10 +836,14 @@ public class CryptoUtil {
 
         aid.encode(tmp);
         tmp.putBitString(signed);
-        out.write(DerValue.tag_Sequence, tmp);
-        X509CertImpl signedCert = new X509CertImpl(out.toByteArray());
+        try (DerOutputStream out = new DerOutputStream()) {
+            out.write(DerValue.tag_Sequence, tmp);
+            X509CertImpl signedCert = new X509CertImpl(out.toByteArray());
+            return signedCert;
+        } catch (CertificateException | IOException e) {
+            throw e;
+        }
 
-        return signedCert;
     }
 
     /**
diff --git a/base/util/src/netscape/security/extensions/AccessDescription.java b/base/util/src/netscape/security/extensions/AccessDescription.java
index f13c937e7ea7995c7e9ace5d5827b6e01cb888d5..f42f3b7f81da78fdb0c2642083c8449a5e50f38d 100644
--- a/base/util/src/netscape/security/extensions/AccessDescription.java
+++ b/base/util/src/netscape/security/extensions/AccessDescription.java
@@ -49,13 +49,16 @@ public class AccessDescription implements Serializable {
      */
     private void writeObject(java.io.ObjectOutputStream out)
             throws IOException {
-        DerOutputStream seq = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream seq = new DerOutputStream();
+             DerOutputStream tmp = new DerOutputStream()) {
 
-        tmp.putOID(mOID);
-        mLocation.encode(tmp);
-        seq.write(DerValue.tag_Sequence, tmp);
-        out.write(seq.toByteArray());
+            tmp.putOID(mOID);
+            mLocation.encode(tmp);
+            seq.write(DerValue.tag_Sequence, tmp);
+            out.write(seq.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java b/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java
index 15c56a04cbce669ae04c9cc26aa000b498389082..800252cebee5385386f33ff0571c41888a4abd50 100644
--- a/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java
+++ b/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java
@@ -184,19 +184,22 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
     }
 
     private void encodeThis() throws IOException {
-        DerOutputStream seq = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream seq = new DerOutputStream();
+             DerOutputStream tmp = new DerOutputStream()) {
 
-        for (int i = 0; i < mDesc.size(); i++) {
-            DerOutputStream tmp0 = new DerOutputStream();
-            AccessDescription ad = mDesc.elementAt(i);
+            for (int i = 0; i < mDesc.size(); i++) {
+                DerOutputStream tmp0 = new DerOutputStream();
+                AccessDescription ad = mDesc.elementAt(i);
 
-            tmp0.putOID(ad.getMethod());
-            ad.getLocation().encode(tmp0);
-            tmp.write(DerValue.tag_Sequence, tmp0);
+                tmp0.putOID(ad.getMethod());
+                ad.getLocation().encode(tmp0);
+                tmp.write(DerValue.tag_Sequence, tmp0);
+            }
+            seq.write(DerValue.tag_Sequence, tmp);
+            this.extensionValue = seq.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        seq.write(DerValue.tag_Sequence, tmp);
-        this.extensionValue = seq.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java b/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java
index 14195945118a1649c025eebcb1f67dcf62b74338..0d0a1ce5309791d1ed763062a4648d8ad40955d8 100644
--- a/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java
+++ b/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java
@@ -148,15 +148,18 @@ public class CertificateRenewalWindowExtension extends Extension
     }
 
     private void encodeThis() throws IOException {
-        DerOutputStream seq = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream seq = new DerOutputStream();
+             DerOutputStream tmp = new DerOutputStream()) {
 
-        tmp.putGeneralizedTime(mBeginTime);
-        if (mEndTime != null) {
-            tmp.putGeneralizedTime(mEndTime);
+            tmp.putGeneralizedTime(mBeginTime);
+            if (mEndTime != null) {
+                tmp.putGeneralizedTime(mEndTime);
+            }
+            seq.write(DerValue.tag_Sequence, tmp);
+            this.extensionValue = seq.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        seq.write(DerValue.tag_Sequence, tmp);
-        this.extensionValue = seq.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java b/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java
index 0f93c2b7801567d94368716ad8830727caca4f34..350fb5365bb248d679b863da453ed41275b01fd0 100644
--- a/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java
+++ b/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java
@@ -147,20 +147,23 @@ public class CertificateScopeOfUseExtension extends Extension
     }
 
     private void encodeThis() throws IOException {
-        DerOutputStream seq = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream seq = new DerOutputStream();
+             DerOutputStream tmp = new DerOutputStream()) {
 
-        if (mEntries == null)
-            throw new IOException("Invalid Scope Entries");
+            if (mEntries == null)
+                throw new IOException("Invalid Scope Entries");
 
-        for (int i = 0; i < mEntries.size(); i++) {
-            CertificateScopeEntry se = mEntries.elementAt(i);
+            for (int i = 0; i < mEntries.size(); i++) {
+                CertificateScopeEntry se = mEntries.elementAt(i);
 
-            se.encode(tmp);
+                se.encode(tmp);
+            }
+
+            seq.write(DerValue.tag_Sequence, tmp);
+            this.extensionValue = seq.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-
-        seq.write(DerValue.tag_Sequence, tmp);
-        this.extensionValue = seq.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java b/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java
index 2ccc53ffd22ecedd28f12e6b87fd8cac288956ad..85f23b30ba9761cf48c0cd7f0a2c3bad11a1421c 100644
--- a/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java
+++ b/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java
@@ -152,21 +152,24 @@ public class InhibitAnyPolicyExtension
     }
 
     public void encode(OutputStream out) throws IOException {
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream os = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        if (this.extensionValue == null) {
-            try {
-                extensionId = ObjectIdentifier.getObjectIdentifier(OID);
-            } catch (IOException e) {
-                // never here
+            if (this.extensionValue == null) {
+                try {
+                    extensionId = ObjectIdentifier.getObjectIdentifier(OID);
+                } catch (IOException e) {
+                    // never here
+                }
+                os.putInteger(mSkipCerts);
+                this.extensionValue = os.toByteArray();
             }
-            DerOutputStream os = new DerOutputStream();
-            os.putInteger(mSkipCerts);
-            this.extensionValue = os.toByteArray();
-        }
 
-        super.encode(tmp);
-        out.write(tmp.toByteArray());
+            super.encode(tmp);
+            out.write(tmp.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     private void encodeExtValue() {
diff --git a/base/util/src/netscape/security/extensions/KerberosName.java b/base/util/src/netscape/security/extensions/KerberosName.java
index a10d70b40dd7ab4bc3fb9c50cf0389965603c0f7..a0549b047fb41153fee7cf22e26e86bd01844358 100644
--- a/base/util/src/netscape/security/extensions/KerberosName.java
+++ b/base/util/src/netscape/security/extensions/KerberosName.java
@@ -69,34 +69,37 @@ public class KerberosName {
      */
     public void encode(OutputStream out) throws IOException {
 
-        DerOutputStream seq = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
-        DerOutputStream realm = new DerOutputStream();
-        realm.putGeneralString(m_realm);
-        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                 true, (byte) 0), realm);
+        try (DerOutputStream seq = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
+            DerOutputStream realm = new DerOutputStream();
+            realm.putGeneralString(m_realm);
+            tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
+                    true, (byte) 0), realm);
 
-        DerOutputStream seq1 = new DerOutputStream();
-        DerOutputStream tmp1 = new DerOutputStream();
-        DerOutputStream name_type = new DerOutputStream();
-        name_type.putInteger(new BigInt(m_name_type));
-        tmp1.write(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                 true, (byte) 0), name_type);
+            DerOutputStream seq1 = new DerOutputStream();
+            DerOutputStream tmp1 = new DerOutputStream();
+            DerOutputStream name_type = new DerOutputStream();
+            name_type.putInteger(new BigInt(m_name_type));
+            tmp1.write(DerValue.createTag(DerValue.TAG_CONTEXT,
+                    true, (byte) 0), name_type);
 
-        DerOutputStream name_strings = new DerOutputStream();
-        DerOutputStream name_string = new DerOutputStream();
-        for (int i = 0; i < m_name_strings.size(); i++) {
-            name_string.putGeneralString(m_name_strings.elementAt(i));
+            DerOutputStream name_strings = new DerOutputStream();
+            DerOutputStream name_string = new DerOutputStream();
+            for (int i = 0; i < m_name_strings.size(); i++) {
+                name_string.putGeneralString(m_name_strings.elementAt(i));
+            }
+            name_strings.write(DerValue.tag_SequenceOf, name_string);
+            tmp1.write(DerValue.createTag(DerValue.TAG_CONTEXT,
+                    true, (byte) 1), name_strings);
+            seq1.write(DerValue.tag_Sequence, tmp1);
+            tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
+                    true, (byte) 1), seq1);
+
+            seq.write(DerValue.tag_Sequence, tmp);
+            out.write(seq.toByteArray());
+        } catch (IOException e) {
+            throw e;
         }
-        name_strings.write(DerValue.tag_SequenceOf, name_string);
-        tmp1.write(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                 true, (byte) 1), name_strings);
-        seq1.write(DerValue.tag_Sequence, tmp1);
-        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                 true, (byte) 1), seq1);
-
-        seq.write(DerValue.tag_Sequence, tmp);
-        out.write(seq.toByteArray());
     }
 
     public byte[] toByteArray() throws IOException {
diff --git a/base/util/src/netscape/security/extensions/NSCertTypeExtension.java b/base/util/src/netscape/security/extensions/NSCertTypeExtension.java
index 1a240f1ce3d0221792741e9191e307549761fa8a..8018cf2d36b2849dce3db24d6e0a12814371701e 100644
--- a/base/util/src/netscape/security/extensions/NSCertTypeExtension.java
+++ b/base/util/src/netscape/security/extensions/NSCertTypeExtension.java
@@ -135,10 +135,13 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
 
     // Encode this extension value
     private void encodeThis() throws IOException {
-        DerOutputStream os = new DerOutputStream();
+        try (DerOutputStream os = new DerOutputStream()) {
 
-        os.putUnalignedBitString(mBitString);
-        this.extensionValue = os.toByteArray();
+            os.putUnalignedBitString(mBitString);
+            this.extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/extensions/PresenceServerExtension.java b/base/util/src/netscape/security/extensions/PresenceServerExtension.java
index 5ee802468ec5aad6de9b32b44085e8447e72ea10..21bbeffa1db7ed5ffcd53a8048fa61b9f03d22bd 100644
--- a/base/util/src/netscape/security/extensions/PresenceServerExtension.java
+++ b/base/util/src/netscape/security/extensions/PresenceServerExtension.java
@@ -130,19 +130,22 @@ public class PresenceServerExtension extends Extension implements CertAttrSet {
     }
 
     public void encodeThis() throws IOException {
-        DerOutputStream out = new DerOutputStream();
-        DerOutputStream temp = new DerOutputStream();
-        temp.putInteger(new BigInt(mVersion));
-        temp.putOctetString(mStreetAddress.getBytes());
-        temp.putOctetString(mTelephoneNumber.getBytes());
-        temp.putOctetString(mRFC822Name.getBytes());
-        temp.putOctetString(mID.getBytes());
-        temp.putOctetString(mHostName.getBytes());
-        temp.putInteger(new BigInt(mPortNumber));
-        temp.putInteger(new BigInt(mMaxUsers));
-        temp.putInteger(new BigInt(mServiceLevel));
-        out.write(DerValue.tag_Sequence, temp);
-        this.extensionValue = out.toByteArray();
+        try (DerOutputStream out = new DerOutputStream()) {
+            DerOutputStream temp = new DerOutputStream();
+            temp.putInteger(new BigInt(mVersion));
+            temp.putOctetString(mStreetAddress.getBytes());
+            temp.putOctetString(mTelephoneNumber.getBytes());
+            temp.putOctetString(mRFC822Name.getBytes());
+            temp.putOctetString(mID.getBytes());
+            temp.putOctetString(mHostName.getBytes());
+            temp.putInteger(new BigInt(mPortNumber));
+            temp.putInteger(new BigInt(mMaxUsers));
+            temp.putInteger(new BigInt(mServiceLevel));
+            out.write(DerValue.tag_Sequence, temp);
+            this.extensionValue = out.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     public void decodeThis() throws IOException {
diff --git a/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java b/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java
index 72407d62eec7575b9b079af03f8dc08db20f921e..acb493d6cc250336c70bf2a0b54a82e26cd76ea8 100644
--- a/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java
+++ b/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java
@@ -166,19 +166,22 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
     }
 
     private void encodeThis() throws IOException {
-        DerOutputStream seq = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream seq = new DerOutputStream();
+                DerOutputStream tmp = new DerOutputStream()) {
 
-        for (int i = 0; i < mDesc.size(); i++) {
-            DerOutputStream tmp0 = new DerOutputStream();
-            AccessDescription ad = mDesc.elementAt(i);
+            for (int i = 0; i < mDesc.size(); i++) {
+                DerOutputStream tmp0 = new DerOutputStream();
+                AccessDescription ad = mDesc.elementAt(i);
 
-            tmp0.putOID(ad.getMethod());
-            ad.getLocation().encode(tmp0);
-            tmp.write(DerValue.tag_Sequence, tmp0);
+                tmp0.putOID(ad.getMethod());
+                ad.getLocation().encode(tmp0);
+                tmp.write(DerValue.tag_Sequence, tmp0);
+            }
+            seq.write(DerValue.tag_Sequence, tmp);
+            this.extensionValue = seq.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        seq.write(DerValue.tag_Sequence, tmp);
-        this.extensionValue = seq.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/pkcs/PKCS10Attribute.java b/base/util/src/netscape/security/pkcs/PKCS10Attribute.java
index c84df2a375beb1b858fb62e19f2d5988901deafd..5d3cfb8c825c6b343facda7a498635a655a97421 100644
--- a/base/util/src/netscape/security/pkcs/PKCS10Attribute.java
+++ b/base/util/src/netscape/security/pkcs/PKCS10Attribute.java
@@ -168,25 +168,28 @@ public class PKCS10Attribute implements DerEncoder, Serializable {
      */
     public void encode(OutputStream out)
             throws CertificateException, IOException {
-        // Encode the attribute value
-        DerOutputStream outAttrValue = new DerOutputStream();
-        attributeValue.encode(outAttrValue);
+        try (DerOutputStream tmp = new DerOutputStream()) {
+            // Encode the attribute value
+            DerOutputStream outAttrValue = new DerOutputStream();
+            attributeValue.encode(outAttrValue);
 
-        // Wrap the encoded attribute value into a SET
-        DerValue outAttrValueSet = new DerValue(DerValue.tag_Set,
-                        outAttrValue.toByteArray());
+            // Wrap the encoded attribute value into a SET
+            DerValue outAttrValueSet = new DerValue(DerValue.tag_Set,
+                    outAttrValue.toByteArray());
 
-        // Create the attribute
-        DerOutputStream outAttr = new DerOutputStream();
-        outAttr.putOID(attributeId);
-        outAttr.putDerValue(outAttrValueSet);
+            // Create the attribute
+            DerOutputStream outAttr = new DerOutputStream();
+            outAttr.putOID(attributeId);
+            outAttr.putDerValue(outAttrValueSet);
 
-        // Wrap the OID and the set of attribute values into a SEQUENCE
-        DerOutputStream tmp = new DerOutputStream();
-        tmp.write(DerValue.tag_Sequence, outAttr);
+            // Wrap the OID and the set of attribute values into a SEQUENCE
+            tmp.write(DerValue.tag_Sequence, outAttr);
 
-        // write the results to out
-        out.write(tmp.toByteArray());
+            // write the results to out
+            out.write(tmp.toByteArray());
+        } catch (CertificateException | IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/pkcs/PKCS10Attributes.java b/base/util/src/netscape/security/pkcs/PKCS10Attributes.java
index 22a0dce21ddc6ca5b65ca770eda338c1d68fb851..4c972187f11848f0eed47640197f5714b48e3312 100644
--- a/base/util/src/netscape/security/pkcs/PKCS10Attributes.java
+++ b/base/util/src/netscape/security/pkcs/PKCS10Attributes.java
@@ -92,16 +92,18 @@ public class PKCS10Attributes extends Vector<PKCS10Attribute> implements DerEnco
      */
     public void derEncode(OutputStream out)
             throws IOException {
+        try (DerOutputStream attrOut = new DerOutputStream()) {
+            // first copy the elements into an array
+            PKCS10Attribute[] attribs = new PKCS10Attribute[size()];
+            copyInto(attribs);
 
-        // first copy the elements into an array
-        PKCS10Attribute[] attribs = new PKCS10Attribute[size()];
-        copyInto(attribs);
+            attrOut.putOrderedSetOf(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
+                    attribs);
 
-        DerOutputStream attrOut = new DerOutputStream();
-        attrOut.putOrderedSetOf(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
-                attribs);
-
-        out.write(attrOut.toByteArray());
+            out.write(attrOut.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/pkcs/PKCS9Attribute.java b/base/util/src/netscape/security/pkcs/PKCS9Attribute.java
index 398fc0174bb797ee5d90a5083bc1f3548d4e504b..703f84cb946056ab8b0476c32e3935fbe2860b83 100644
--- a/base/util/src/netscape/security/pkcs/PKCS9Attribute.java
+++ b/base/util/src/netscape/security/pkcs/PKCS9Attribute.java
@@ -758,116 +758,114 @@ public class PKCS9Attribute implements DerEncoder {
      * <code>PrintableString</code>s, without checking whether they should be encoded as <code>T61String</code>s.
      */
     public void derEncode(OutputStream out) throws IOException {
-        DerOutputStream temp = new DerOutputStream();
-        temp.putOID(getOID());
-        switch (index) {
-        case 1: // email address
-        case 2: // unstructured name
-        { // open scope
-            String[] values = (String[]) value;
-            DerOutputStream[] temps = new
-                    DerOutputStream[values.length];
-
-            for (int i = 0; i < values.length; i++) {
-                temps[i] = new DerOutputStream();
-
-                temps[i].putIA5String(values[i]);
+        try (DerOutputStream temp = new DerOutputStream(); DerOutputStream temp2 = new DerOutputStream();
+                DerOutputStream derOut = new DerOutputStream()) {
+            temp.putOID(getOID());
+            switch (index) {
+            case 1: // email address
+            case 2: // unstructured name
+            { // open scope
+                String[] values = (String[]) value;
+                DerOutputStream[] temps = new
+                        DerOutputStream[values.length];
+
+                for (int i = 0; i < values.length; i++) {
+                    temps[i] = new DerOutputStream();
+
+                    temps[i].putIA5String(values[i]);
+                }
+                temp.putOrderedSetOf(DerValue.tag_Set, temps);
+            } // close scope
+                break;
+
+            case 3: // content type
+            {
+                temp2.putOID((ObjectIdentifier) value);
+                temp.write(DerValue.tag_Set, temp2.toByteArray());
             }
-            temp.putOrderedSetOf(DerValue.tag_Set, temps);
-        } // close scope
-            break;
-
-        case 3: // content type
-        {
-            DerOutputStream temp2 = new DerOutputStream();
-            temp2.putOID((ObjectIdentifier) value);
-            temp.write(DerValue.tag_Set, temp2.toByteArray());
-        }
-            break;
-
-        case 4: // message digest
-        {
-            DerOutputStream temp2 = new DerOutputStream();
-            temp2.putOctetString((byte[]) value);
-            temp.write(DerValue.tag_Set, temp2.toByteArray());
-        }
-            break;
-
-        case 5: // signing time
-        {
-            DerOutputStream temp2 = new DerOutputStream();
-            temp2.putUTCTime((Date) value);
-            temp.write(DerValue.tag_Set, temp2.toByteArray());
-        }
-            break;
-
-        case 6: // countersignature
-            temp.putOrderedSetOf(DerValue.tag_Set, (DerEncoder[]) value);
-            break;
+                break;
 
-        case 7: // challenge password
-        {
-            DerOutputStream temp2 = new DerOutputStream();
-            temp2.putPrintableString((String) value);
-            temp.write(DerValue.tag_Set, temp2.toByteArray());
-        }
-            break;
+            case 4: // message digest
+            {
+                temp2.putOctetString((byte[]) value);
+                temp.write(DerValue.tag_Set, temp2.toByteArray());
+            }
+                break;
 
-        case 8: // unstructured address
-        { // open scope
-            String[] values = (String[]) value;
-            DerOutputStream[] temps = new
-                    DerOutputStream[values.length];
+            case 5: // signing time
+            {
+                temp2.putUTCTime((Date) value);
+                temp.write(DerValue.tag_Set, temp2.toByteArray());
+            }
+                break;
 
-            for (int i = 0; i < values.length; i++) {
-                temps[i] = new DerOutputStream();
+            case 6: // countersignature
+                temp.putOrderedSetOf(DerValue.tag_Set, (DerEncoder[]) value);
+                break;
 
-                temps[i].putPrintableString(values[i]);
+            case 7: // challenge password
+            {
+                temp2.putPrintableString((String) value);
+                temp.write(DerValue.tag_Set, temp2.toByteArray());
             }
-            temp.putOrderedSetOf(DerValue.tag_Set, temps);
-        } // close scope
-            break;
-
-        case 9: // extended-certificate attribute -- not
-            // supported
-            throw new IOException("PKCS9 extended-certificate " +
-                    "attribute not supported.");
-
-        case 10: // IssuerAndSerialNumber attribute -- not
-            // supported
-            throw new IOException("PKCS9 IssuerAndSerialNumber " +
-                    "attribute not supported.");
-
-        case 11: // passwordCheck attribute -- not
-            // supported
-            throw new IOException("PKCS9 passwordCheck " +
-                    "attribute not supported.");
-        case 12: // PublicKey attribute -- not
-            // supported
-            throw new IOException("PKCS9 PublicKey " +
-                    "attribute not supported.");
-        case 13: // SigningDescription attribute -- not
-            // supported
-            throw new IOException("PKCS9 SigningDescription " +
-                    "attribute not supported.");
-        case 14: // ExtensionRequest attribute
-            try {
-                DerOutputStream temp2 = new DerOutputStream();
-                //temp2.putSequence((CertificateExtensions) value);
-                ((CertificateExtensions) value).encode(temp2);
-                temp.write(DerValue.tag_Sequence, temp2.toByteArray());
-            } catch (CertificateException e) {
-                throw new IOException("PKCS9 extension attributes not encoded");
+                break;
+
+            case 8: // unstructured address
+            { // open scope
+                String[] values = (String[]) value;
+                DerOutputStream[] temps = new
+                        DerOutputStream[values.length];
+
+                for (int i = 0; i < values.length; i++) {
+                    temps[i] = new DerOutputStream();
+
+                    temps[i].putPrintableString(values[i]);
+                }
+                temp.putOrderedSetOf(DerValue.tag_Set, temps);
+            } // close scope
+                break;
+
+            case 9: // extended-certificate attribute -- not
+                // supported
+                throw new IOException("PKCS9 extended-certificate " +
+                        "attribute not supported.");
+
+            case 10: // IssuerAndSerialNumber attribute -- not
+                // supported
+                throw new IOException("PKCS9 IssuerAndSerialNumber " +
+                        "attribute not supported.");
+
+            case 11: // passwordCheck attribute -- not
+                // supported
+                throw new IOException("PKCS9 passwordCheck " +
+                        "attribute not supported.");
+            case 12: // PublicKey attribute -- not
+                // supported
+                throw new IOException("PKCS9 PublicKey " +
+                        "attribute not supported.");
+            case 13: // SigningDescription attribute -- not
+                // supported
+                throw new IOException("PKCS9 SigningDescription " +
+                        "attribute not supported.");
+            case 14: // ExtensionRequest attribute
+                try {
+                    //temp2.putSequence((CertificateExtensions) value);
+                    ((CertificateExtensions) value).encode(temp2);
+                    temp.write(DerValue.tag_Sequence, temp2.toByteArray());
+                } catch (CertificateException e) {
+                    throw new IOException("PKCS9 extension attributes not encoded");
+                }
+
+                // break unnecessary
+            default: // can't happen
             }
 
-            // break unnecessary
-        default: // can't happen
-        }
-
-        DerOutputStream derOut = new DerOutputStream();
-        derOut.write(DerValue.tag_Sequence, temp.toByteArray());
+            derOut.write(DerValue.tag_Sequence, temp.toByteArray());
 
-        out.write(derOut.toByteArray());
+            out.write(derOut.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
 
     }
 
diff --git a/base/util/src/netscape/security/pkcs/PKCS9Attributes.java b/base/util/src/netscape/security/pkcs/PKCS9Attributes.java
index 35996b4b68b0e11483c10a6daa93696e5e517601..7777962cb397a9640e020909fd1aef7251c59061 100644
--- a/base/util/src/netscape/security/pkcs/PKCS9Attributes.java
+++ b/base/util/src/netscape/security/pkcs/PKCS9Attributes.java
@@ -191,12 +191,15 @@ public class PKCS9Attributes {
     }
 
     private byte[] generateDerEncoding() throws IOException {
-        DerOutputStream out = new DerOutputStream();
-        Object[] attribVals = attributes.values().toArray();
+        try (DerOutputStream out = new DerOutputStream()) {
+            Object[] attribVals = attributes.values().toArray();
 
-        out.putOrderedSetOf(DerValue.tag_SetOf,
-                castToDerEncoder(attribVals));
-        return out.toByteArray();
+            out.putOrderedSetOf(DerValue.tag_SetOf,
+                    castToDerEncoder(attribVals));
+            return out.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/pkcs/SignerInfo.java b/base/util/src/netscape/security/pkcs/SignerInfo.java
index 794033c8774fb8b04558322bb1c8218231f25821..83b77bef1b74d7aad5e34f15cfc6105b0386f349 100644
--- a/base/util/src/netscape/security/pkcs/SignerInfo.java
+++ b/base/util/src/netscape/security/pkcs/SignerInfo.java
@@ -148,31 +148,34 @@ public class SignerInfo implements DerEncoder {
      * @exception IOException on encoding error.
      */
     public void derEncode(OutputStream out) throws IOException {
-        DerOutputStream seq = new DerOutputStream();
-        seq.putInteger(version);
-        DerOutputStream issuerAndSerialNumber = new DerOutputStream();
-        issuerName.encode(issuerAndSerialNumber);
-        issuerAndSerialNumber.putInteger(certificateSerialNumber);
-        seq.write(DerValue.tag_Sequence, issuerAndSerialNumber);
+        try (DerOutputStream tmp = new DerOutputStream()) {
+            DerOutputStream seq = new DerOutputStream();
+            seq.putInteger(version);
+            DerOutputStream issuerAndSerialNumber = new DerOutputStream();
+            issuerName.encode(issuerAndSerialNumber);
+            issuerAndSerialNumber.putInteger(certificateSerialNumber);
+            seq.write(DerValue.tag_Sequence, issuerAndSerialNumber);
 
-        digestAlgorithmId.encode(seq);
+            digestAlgorithmId.encode(seq);
 
-        // encode authenticated attributes if there are any
-        if (authenticatedAttributes != null)
-            authenticatedAttributes.encode((byte) 0xA0, seq);
+            // encode authenticated attributes if there are any
+            if (authenticatedAttributes != null)
+                authenticatedAttributes.encode((byte) 0xA0, seq);
 
-        digestEncryptionAlgorithmId.encode(seq);
+            digestEncryptionAlgorithmId.encode(seq);
 
-        seq.putOctetString(encryptedDigest);
+            seq.putOctetString(encryptedDigest);
 
-        // encode unauthenticated attributes if there are any
-        if (unauthenticatedAttributes != null)
-            unauthenticatedAttributes.encode((byte) 0xA1, seq);
+            // encode unauthenticated attributes if there are any
+            if (unauthenticatedAttributes != null)
+                unauthenticatedAttributes.encode((byte) 0xA1, seq);
 
-        DerOutputStream tmp = new DerOutputStream();
-        tmp.write(DerValue.tag_Sequence, seq);
+            tmp.write(DerValue.tag_Sequence, seq);
 
-        out.write(tmp.toByteArray());
+            out.write(tmp.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     public X509Certificate getCertificate(PKCS7 block)
diff --git a/base/util/src/netscape/security/provider/DSA.java b/base/util/src/netscape/security/provider/DSA.java
index 9403475e0b3ab5cf0b19dd34b95731de3f1f1c25..5599ae33bceeb3b1d2e18254111f95e20b6a6710 100644
--- a/base/util/src/netscape/security/provider/DSA.java
+++ b/base/util/src/netscape/security/provider/DSA.java
@@ -163,8 +163,7 @@ public final class DSA extends Signature {
         BigInt rAsBigInt = new BigInt(r.toByteArray());
         BigInt sAsBigInt = new BigInt(s.toByteArray());
 
-        try {
-            DerOutputStream outseq = new DerOutputStream(100);
+        try (DerOutputStream outseq = new DerOutputStream(100)) {
             outseq.putInteger(rAsBigInt);
             outseq.putInteger(sAsBigInt);
             DerValue result = new DerValue(DerValue.tag_Sequence,
diff --git a/base/util/src/netscape/security/provider/DSAParameters.java b/base/util/src/netscape/security/provider/DSAParameters.java
index d22ab10fc13784212d420b54b82acd57f8bdfe2c..0d3f16ef64f08db6cf04f3be3f95d66170405dd1 100755
--- a/base/util/src/netscape/security/provider/DSAParameters.java
+++ b/base/util/src/netscape/security/provider/DSAParameters.java
@@ -103,14 +103,17 @@ public class DSAParameters extends AlgorithmParametersSpi {
     }
 
     protected byte[] engineGetEncoded() throws IOException {
-        DerOutputStream out = new DerOutputStream();
-        DerOutputStream bytes = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()) {
+            DerOutputStream bytes = new DerOutputStream();
 
-        bytes.putInteger(new BigInt(p.toByteArray()));
-        bytes.putInteger(new BigInt(q.toByteArray()));
-        bytes.putInteger(new BigInt(g.toByteArray()));
-        out.write(DerValue.tag_Sequence, bytes);
-        return out.toByteArray();
+            bytes.putInteger(new BigInt(p.toByteArray()));
+            bytes.putInteger(new BigInt(q.toByteArray()));
+            bytes.putInteger(new BigInt(g.toByteArray()));
+            out.write(DerValue.tag_Sequence, bytes);
+            return out.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     protected byte[] engineGetEncoded(String encodingMethod)
diff --git a/base/util/src/netscape/security/provider/RSAPublicKey.java b/base/util/src/netscape/security/provider/RSAPublicKey.java
index bd5aa2fe4f028e0b801babe6a4dd5e1a33610f2a..b3c10f56274cb98c4cd135fddaa6b17e03b068d5 100644
--- a/base/util/src/netscape/security/provider/RSAPublicKey.java
+++ b/base/util/src/netscape/security/provider/RSAPublicKey.java
@@ -73,9 +73,7 @@ public final class RSAPublicKey extends X509Key implements Serializable {
         this.publicExponent = publicExponent;
         this.algid = new AlgorithmId(ALGORITHM_OID);
 
-        try {
-            DerOutputStream out = new DerOutputStream();
-
+        try (DerOutputStream out = new DerOutputStream()) {
             out.putInteger(modulus);
             out.putInteger(publicExponent);
             key = (new DerValue(DerValue.tag_Sequence,
diff --git a/base/util/src/netscape/security/x509/AVA.java b/base/util/src/netscape/security/x509/AVA.java
index 534f7c212094bf3423423be7248e11da2229ae84..d56bd95cadc4416053846198fedd0938efbb1e38 100644
--- a/base/util/src/netscape/security/x509/AVA.java
+++ b/base/util/src/netscape/security/x509/AVA.java
@@ -232,13 +232,16 @@ public final class AVA implements DerEncoder {
      * @exception IOException on encoding error.
      */
     public void derEncode(OutputStream out) throws IOException {
-        DerOutputStream tmp = new DerOutputStream();
-        DerOutputStream tmp2 = new DerOutputStream();
+        try (DerOutputStream tmp2 = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        tmp.putOID(oid);
-        value.encode(tmp);
-        tmp2.write(DerValue.tag_Sequence, tmp);
-        out.write(tmp2.toByteArray());
+            tmp.putOID(oid);
+            value.encode(tmp);
+            tmp2.write(DerValue.tag_Sequence, tmp);
+            out.write(tmp2.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/AlgIdDSA.java b/base/util/src/netscape/security/x509/AlgIdDSA.java
index ed2a73de0e362b81e41bb60fcab1f985697470ca..30777dcb6f418974fdb0c51dd0e4b15192742dc6 100644
--- a/base/util/src/netscape/security/x509/AlgIdDSA.java
+++ b/base/util/src/netscape/security/x509/AlgIdDSA.java
@@ -130,12 +130,14 @@ public final class AlgIdDSA extends AlgorithmId implements DSAParams {
      */
     private void initializeParams()
             throws IOException {
-        DerOutputStream out = new DerOutputStream();
-
-        out.putInteger(new BigInt(p.toByteArray()));
-        out.putInteger(new BigInt(q.toByteArray()));
-        out.putInteger(new BigInt(g.toByteArray()));
-        params = new DerValue(DerValue.tag_Sequence, out.toByteArray());
+        try (DerOutputStream out = new DerOutputStream()) {
+            out.putInteger(new BigInt(p.toByteArray()));
+            out.putInteger(new BigInt(q.toByteArray()));
+            out.putInteger(new BigInt(g.toByteArray()));
+            params = new DerValue(DerValue.tag_Sequence, out.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/AlgorithmId.java b/base/util/src/netscape/security/x509/AlgorithmId.java
index a027c19cc2cd6192ddfabe267f3dd15604412ba0..eb2c0413fd56f6a017229b58004a4e322d9519e9 100644
--- a/base/util/src/netscape/security/x509/AlgorithmId.java
+++ b/base/util/src/netscape/security/x509/AlgorithmId.java
@@ -227,16 +227,18 @@ public class AlgorithmId implements Serializable, DerEncoder {
      * @exception IOException on encoding error.
      */
     public void derEncode(OutputStream out) throws IOException {
-        DerOutputStream bytes = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
-
-        bytes.putOID(algid);
-        if (params == null)
-            bytes.putNull();
-        else
-            bytes.putDerValue(params);
-        tmp.write(DerValue.tag_Sequence, bytes);
-        out.write(tmp.toByteArray());
+        try (DerOutputStream tmp = new DerOutputStream()) {
+            DerOutputStream bytes = new DerOutputStream();
+            bytes.putOID(algid);
+            if (params == null)
+                bytes.putNull();
+            else
+                bytes.putDerValue(params);
+            tmp.write(DerValue.tag_Sequence, bytes);
+            out.write(tmp.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     // XXXX cleaning required
@@ -244,16 +246,19 @@ public class AlgorithmId implements Serializable, DerEncoder {
      * Returns the DER-encoded X.509 AlgorithmId as a byte array.
      */
     public final byte[] encode() throws IOException {
-        DerOutputStream out = new DerOutputStream();
-        DerOutputStream bytes = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()) {
+            DerOutputStream bytes = new DerOutputStream();
 
-        bytes.putOID(algid);
-        if (params == null)
-            bytes.putNull();
-        else
-            bytes.putDerValue(params);
-        out.write(DerValue.tag_Sequence, bytes);
-        return out.toByteArray();
+            bytes.putOID(algid);
+            if (params == null)
+                bytes.putNull();
+            else
+                bytes.putDerValue(params);
+            out.write(DerValue.tag_Sequence, bytes);
+            return out.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/Attribute.java b/base/util/src/netscape/security/x509/Attribute.java
index 760d0a805e2b40b5eaa6def0164af0b4943591c9..6f57213e649e3d6d6e4a71516122c13d0211e302 100644
--- a/base/util/src/netscape/security/x509/Attribute.java
+++ b/base/util/src/netscape/security/x509/Attribute.java
@@ -229,38 +229,44 @@ public final class Attribute implements Serializable, DerEncoder {
     //encode the attribute object
     private void encodeThis(OutputStream out)
             throws IOException {
-        DerOutputStream tmp = new DerOutputStream();
-        DerOutputStream tmp2 = new DerOutputStream();
+        try (DerOutputStream tmp2 = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        tmp.putOID(oid);
-        encodeValueSet(tmp);
-        tmp2.write(DerValue.tag_Sequence, tmp);
-        out.write(tmp2.toByteArray());
+            tmp.putOID(oid);
+            encodeValueSet(tmp);
+            tmp2.write(DerValue.tag_Sequence, tmp);
+            out.write(tmp2.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     //encode the attribute object
     private void encodeValueSet(OutputStream out)
             throws IOException {
-        DerOutputStream tmp = new DerOutputStream();
-        DerOutputStream tmp2 = new DerOutputStream();
+        try (DerOutputStream tmp2 = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        //get the attribute converter
-        AVAValueConverter converter = attrMap.getValueConverter(oid);
-        if (converter == null) {
-            converter = new GenericValueConverter();
-            //throw new IOException("Converter not found: unsupported attribute type");
-        }
+            //get the attribute converter
+            AVAValueConverter converter = attrMap.getValueConverter(oid);
+            if (converter == null) {
+                converter = new GenericValueConverter();
+                //throw new IOException("Converter not found: unsupported attribute type");
+            }
 
-        //loop through all the values and encode
-        Enumeration<String> vals = valueSet.elements();
-        while (vals.hasMoreElements()) {
-            String val = vals.nextElement();
-            DerValue derobj = converter.getValue(val);
-            derobj.encode(tmp);
-        }
+            //loop through all the values and encode
+            Enumeration<String> vals = valueSet.elements();
+            while (vals.hasMoreElements()) {
+                String val = vals.nextElement();
+                DerValue derobj = converter.getValue(val);
+                derobj.encode(tmp);
+            }
 
-        tmp2.write(DerValue.tag_SetOf, tmp);
-        out.write(tmp2.toByteArray());
+            tmp2.write(DerValue.tag_SetOf, tmp);
+            out.write(tmp2.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     //decode the attribute object
diff --git a/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java b/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java
index a8df9d132f120cfef4b0e901742f7c1bcd6a41b2..23552a5c88b722e83cb72a16a8b83df8ec30dfbc 100644
--- a/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java
+++ b/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java
@@ -83,32 +83,36 @@ public class AuthorityKeyIdentifierExtension extends Extension
 
     // Encode only the extension value
     private void encodeThis() throws IOException {
-        DerOutputStream seq = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
-        if (id != null) {
-            DerOutputStream tmp1 = new DerOutputStream();
-            id.encode(tmp1);
-            tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                              false, TAG_ID), tmp1);
-        }
-        try {
-            if (names != null) {
+        try (DerOutputStream tmp = new DerOutputStream();
+                DerOutputStream seq = new DerOutputStream()) {
+
+            if (id != null) {
                 DerOutputStream tmp1 = new DerOutputStream();
-                names.encode(tmp1);
+                id.encode(tmp1);
                 tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                  true, TAG_NAMES), tmp1);
+                        false, TAG_ID), tmp1);
             }
-        } catch (Exception e) {
-            throw new IOException(e.toString());
-        }
-        if (serialNum != null) {
-            DerOutputStream tmp1 = new DerOutputStream();
-            serialNum.encode(tmp1);
-            tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                              false, TAG_SERIAL_NUM), tmp1);
+            try {
+                if (names != null) {
+                    DerOutputStream tmp1 = new DerOutputStream();
+                    names.encode(tmp1);
+                    tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+                            true, TAG_NAMES), tmp1);
+                }
+            } catch (Exception e) {
+                throw new IOException(e.toString());
+            }
+            if (serialNum != null) {
+                DerOutputStream tmp1 = new DerOutputStream();
+                serialNum.encode(tmp1);
+                tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+                        false, TAG_SERIAL_NUM), tmp1);
+            }
+            seq.write(DerValue.tag_Sequence, tmp);
+            this.extensionValue = seq.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        seq.write(DerValue.tag_Sequence, tmp);
-        this.extensionValue = seq.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/BasicConstraintsExtension.java b/base/util/src/netscape/security/x509/BasicConstraintsExtension.java
index 8f3a3c6346b29554740f70f401300041f85fee37..001b148b1b187b2bf3e7edf32b88eaa7865e2e26 100644
--- a/base/util/src/netscape/security/x509/BasicConstraintsExtension.java
+++ b/base/util/src/netscape/security/x509/BasicConstraintsExtension.java
@@ -73,17 +73,20 @@ public class BasicConstraintsExtension extends Extension
 
     // Encode this extension value
     private void encodeThis() throws IOException {
-        DerOutputStream out = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        if (ca) {
-            tmp.putBoolean(ca);
+            if (ca) {
+                tmp.putBoolean(ca);
+            }
+            if (pathLen >= 0) {
+                tmp.putInteger(new BigInt(pathLen));
+            }
+            out.write(DerValue.tag_Sequence, tmp);
+            this.extensionValue = out.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        if (pathLen >= 0) {
-            tmp.putInteger(new BigInt(pathLen));
-        }
-        out.write(DerValue.tag_Sequence, tmp);
-        this.extensionValue = out.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/CRLNumberExtension.java b/base/util/src/netscape/security/x509/CRLNumberExtension.java
index 4cacde942cdac89236cfc1dc3d6f4e631fca6176..63289513f2f52c3e63d54164334627e130b9cead 100755
--- a/base/util/src/netscape/security/x509/CRLNumberExtension.java
+++ b/base/util/src/netscape/security/x509/CRLNumberExtension.java
@@ -61,9 +61,12 @@ public class CRLNumberExtension extends Extension
     private void encodeThis() throws IOException {
         if (crlNumber == null)
             throw new IOException("Unintialized CRL number extension");
-        DerOutputStream os = new DerOutputStream();
-        os.putInteger(this.crlNumber);
-        this.extensionValue = os.toByteArray();
+        try (DerOutputStream os = new DerOutputStream()) {
+            os.putInteger(this.crlNumber);
+            this.extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/CRLReasonExtension.java b/base/util/src/netscape/security/x509/CRLReasonExtension.java
index 77339528e4b640814c7cf0dca8897b5603f049fe..59cd45d911e70b607082412fcdec5fc519052760 100644
--- a/base/util/src/netscape/security/x509/CRLReasonExtension.java
+++ b/base/util/src/netscape/security/x509/CRLReasonExtension.java
@@ -181,9 +181,12 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet {
     private void encodeThis() throws IOException {
         if (mReason == null)
             throw new IOException("Unintialized CRLReason extension");
-        DerOutputStream os = new DerOutputStream();
-        os.putEnumerated(mReason.toInt());
-        this.extensionValue = os.toByteArray();
+        try (DerOutputStream os = new DerOutputStream()) {
+            os.putEnumerated(mReason.toInt());
+            this.extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/CertificateExtensions.java b/base/util/src/netscape/security/x509/CertificateExtensions.java
index 5fdac282426772c9d21abc3982c59a1e788f7ca0..e8cd5bfb443f3c227e0399e6e80bfb84a4175bb4 100644
--- a/base/util/src/netscape/security/x509/CertificateExtensions.java
+++ b/base/util/src/netscape/security/x509/CertificateExtensions.java
@@ -187,25 +187,28 @@ public class CertificateExtensions extends Vector<Extension>
      */
     public void encode(OutputStream out)
             throws CertificateException, IOException {
-        DerOutputStream extOut = new DerOutputStream();
-        for (int i = 0; i < size(); i++) {
-            Object thisOne = elementAt(i);
-            if (thisOne instanceof CertAttrSet)
-                ((CertAttrSet) thisOne).encode(extOut);
-            else if (thisOne instanceof Extension)
-                ((Extension) thisOne).encode(extOut);
-            else
-                throw new CertificateException("Invalid extension object");
+        try (DerOutputStream tmp = new DerOutputStream()) {
+            DerOutputStream extOut = new DerOutputStream();
+            for (int i = 0; i < size(); i++) {
+                Object thisOne = elementAt(i);
+                if (thisOne instanceof CertAttrSet)
+                    ((CertAttrSet) thisOne).encode(extOut);
+                else if (thisOne instanceof Extension)
+                    ((Extension) thisOne).encode(extOut);
+                else
+                    throw new CertificateException("Invalid extension object");
+            }
+
+            DerOutputStream seq = new DerOutputStream();
+            seq.write(DerValue.tag_Sequence, extOut);
+
+            tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3),
+                    seq);
+
+            out.write(tmp.toByteArray());
+        } catch (IOException | CertificateException e) {
+            throw e;
         }
-
-        DerOutputStream seq = new DerOutputStream();
-        seq.write(DerValue.tag_Sequence, extOut);
-
-        DerOutputStream tmp = new DerOutputStream();
-        tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3),
-                  seq);
-
-        out.write(tmp.toByteArray());
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java b/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java
index 8d45fd1108d812397d3f6e624f602fb4077a371c..7b3faa1d374c142d8067f8e31b438bb90077e399 100644
--- a/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java
+++ b/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java
@@ -74,14 +74,17 @@ public class CertificatePoliciesExtension extends Extension
 
     // Encode this extension value
     private void encodeThis() throws IOException {
-        DerOutputStream os = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream os = new DerOutputStream();) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        for (int i = 0; i < mInfos.size(); i++) {
-            mInfos.elementAt(i).encode(tmp);
+            for (int i = 0; i < mInfos.size(); i++) {
+                mInfos.elementAt(i).encode(tmp);
+            }
+            os.write(DerValue.tag_Sequence, tmp);
+            extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        os.write(DerValue.tag_Sequence, tmp);
-        extensionValue = os.toByteArray();
     }
 
     public CertificatePoliciesExtension(boolean critical, Vector<CertificatePolicyInfo> infos) throws IOException {
diff --git a/base/util/src/netscape/security/x509/CertificateValidity.java b/base/util/src/netscape/security/x509/CertificateValidity.java
index ae24979c5d07eb4875d59ca3bb412932e6fb37cd..27accc1162187e5c6f73743c2e6737531b5b15ca 100644
--- a/base/util/src/netscape/security/x509/CertificateValidity.java
+++ b/base/util/src/netscape/security/x509/CertificateValidity.java
@@ -169,29 +169,30 @@ public class CertificateValidity implements CertAttrSet, Serializable {
      * @exception IOException on errors.
      */
     public void encode(OutputStream out) throws IOException {
-
         // in cases where default constructor is used check for
         // null values
         if (notBefore == null || notAfter == null) {
             throw new IOException("CertAttrSet:CertificateValidity:" +
-                                  " null values to encode.\n");
+                    " null values to encode.\n");
         }
-        DerOutputStream pair = new DerOutputStream();
+        try (DerOutputStream pair = new DerOutputStream();
+                DerOutputStream seq = new DerOutputStream()) {
+            if (notBefore.getTime() < YR_2050) {
+                pair.putUTCTime(notBefore);
+            } else
+                pair.putGeneralizedTime(notBefore);
 
-        if (notBefore.getTime() < YR_2050) {
-            pair.putUTCTime(notBefore);
-        } else
-            pair.putGeneralizedTime(notBefore);
+            if (notAfter.getTime() < YR_2050) {
+                pair.putUTCTime(notAfter);
+            } else {
+                pair.putGeneralizedTime(notAfter);
+            }
+            seq.write(DerValue.tag_Sequence, pair);
 
-        if (notAfter.getTime() < YR_2050) {
-            pair.putUTCTime(notAfter);
-        } else {
-            pair.putGeneralizedTime(notAfter);
+            out.write(seq.toByteArray());
+        } catch (IOException e) {
+            throw e;
         }
-        DerOutputStream seq = new DerOutputStream();
-        seq.write(DerValue.tag_Sequence, pair);
-
-        out.write(seq.toByteArray());
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/CertificateVersion.java b/base/util/src/netscape/security/x509/CertificateVersion.java
index 5cc260d7717f87edcdaff6dcde55aebb8e7ff680..890cd7b9773f6599bc50d3de4b0440547fc6b39e 100644
--- a/base/util/src/netscape/security/x509/CertificateVersion.java
+++ b/base/util/src/netscape/security/x509/CertificateVersion.java
@@ -160,14 +160,17 @@ public class CertificateVersion implements CertAttrSet {
         if (version == V1) {
             return;
         }
-        DerOutputStream tmp = new DerOutputStream();
-        tmp.putInteger(new BigInt(version));
+        try (DerOutputStream tmp = new DerOutputStream();
+                DerOutputStream seq = new DerOutputStream()) {
+            tmp.putInteger(new BigInt(version));
 
-        DerOutputStream seq = new DerOutputStream();
-        seq.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
-                  tmp);
+            seq.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
+                    tmp);
 
-        out.write(seq.toByteArray());
+            out.write(seq.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java b/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java
index 4b64d59a93ac15b74d38eb03982c775aaa83fe23..02e91914cb7a4f39dede9f6c252aac6553bc271d 100755
--- a/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java
+++ b/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java
@@ -73,9 +73,12 @@ public class DeltaCRLIndicatorExtension extends Extension
     private void encodeThis() throws IOException {
         if (baseCRLNumber == null)
             throw new IOException("Unintialized delta CRL indicator extension");
-        DerOutputStream os = new DerOutputStream();
-        os.putInteger(this.baseCRLNumber);
-        this.extensionValue = os.toByteArray();
+        try (DerOutputStream os = new DerOutputStream()) {
+            os.putInteger(this.baseCRLNumber);
+            this.extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/Extension.java b/base/util/src/netscape/security/x509/Extension.java
index c7b0aa887744c5b39b0391916c56753931bd414f..43bbafe8171e89185e07d35fa7a8b86971716cec 100644
--- a/base/util/src/netscape/security/x509/Extension.java
+++ b/base/util/src/netscape/security/x509/Extension.java
@@ -123,11 +123,10 @@ public class Extension implements Serializable {
      * @exception IOException on encoding errors
      */
     public void encode(DerOutputStream out) throws IOException {
-        DerOutputStream bytes = new DerOutputStream();
-
         if (extensionId == null)
             throw new IOException("Null OID to encode for the extension!");
 
+        DerOutputStream bytes = new DerOutputStream();
         bytes.putOID(extensionId);
         if (critical)
             bytes.putBoolean(critical);
diff --git a/base/util/src/netscape/security/x509/Extensions.java b/base/util/src/netscape/security/x509/Extensions.java
index 109f795e906dfcba8eacd84cf905681ee901533c..c6173e659b2af1fcdbf2f9baf07bda0541320c8e 100644
--- a/base/util/src/netscape/security/x509/Extensions.java
+++ b/base/util/src/netscape/security/x509/Extensions.java
@@ -162,10 +162,13 @@ public class Extensions extends Vector<Extension>
                 throw new CertificateException("Invalid extension object");
         }
 
-        DerOutputStream seq = new DerOutputStream();
-        seq.write(DerValue.tag_Sequence, extOut);
+        try (DerOutputStream seq = new DerOutputStream()) {
+            seq.write(DerValue.tag_Sequence, extOut);
 
-        out.write(seq.toByteArray());
+            out.write(seq.toByteArray());
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/HoldInstructionExtension.java b/base/util/src/netscape/security/x509/HoldInstructionExtension.java
index 82e8475af4dfed4cdd62c56215facec6f5f066ec..5aa9bf1255cc484771b0c3f1949dbfd258135abc 100644
--- a/base/util/src/netscape/security/x509/HoldInstructionExtension.java
+++ b/base/util/src/netscape/security/x509/HoldInstructionExtension.java
@@ -113,9 +113,13 @@ public class HoldInstructionExtension extends Extension
     private void encodeThis() throws IOException {
         if (holdInstructionCodeOID == null)
             throw new IOException("Unintialized hold instruction extension");
-        DerOutputStream os = new DerOutputStream();
-        os.putOID(holdInstructionCodeOID);
-        this.extensionValue = os.toByteArray();
+
+        try (DerOutputStream os = new DerOutputStream()) {
+            os.putOID(holdInstructionCodeOID);
+            this.extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/InvalidityDateExtension.java b/base/util/src/netscape/security/x509/InvalidityDateExtension.java
index 8a973038597f2039e86d5c7a73d78cab5d5fefdd..e667f5530c027c62ae3319b88ccee9ad6b137e1b 100755
--- a/base/util/src/netscape/security/x509/InvalidityDateExtension.java
+++ b/base/util/src/netscape/security/x509/InvalidityDateExtension.java
@@ -74,9 +74,12 @@ public class InvalidityDateExtension extends Extension
     private void encodeThis() throws IOException {
         if (invalidityDate == null)
             throw new IOException("Unintialized invalidity date extension");
-        DerOutputStream os = new DerOutputStream();
-        os.putGeneralizedTime(this.invalidityDate);
-        this.extensionValue = os.toByteArray();
+        try (DerOutputStream os = new DerOutputStream()) {
+            os.putGeneralizedTime(this.invalidityDate);
+            this.extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/KeyUsageExtension.java b/base/util/src/netscape/security/x509/KeyUsageExtension.java
index 8cbfc880aed6ecb33aab628357536e6f1e12918d..6e5c3d82c394fa857b51175eaf00caeb1acf1e3a 100644
--- a/base/util/src/netscape/security/x509/KeyUsageExtension.java
+++ b/base/util/src/netscape/security/x509/KeyUsageExtension.java
@@ -99,9 +99,12 @@ public class KeyUsageExtension extends Extension
 
     // Encode this extension value
     private void encodeThis() throws IOException {
-        DerOutputStream os = new DerOutputStream();
-        os.putUnalignedBitString(this.bitString);
-        this.extensionValue = os.toByteArray();
+        try (DerOutputStream os = new DerOutputStream()) {
+            os.putUnalignedBitString(this.bitString);
+            this.extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/NSCCommentExtension.java b/base/util/src/netscape/security/x509/NSCCommentExtension.java
index 6ba4775049ec2f401ccd139864cda27b88977f15..62ff39dc43caebd64497c1745f2c2bd54e20e854 100644
--- a/base/util/src/netscape/security/x509/NSCCommentExtension.java
+++ b/base/util/src/netscape/security/x509/NSCCommentExtension.java
@@ -63,12 +63,14 @@ public class NSCCommentExtension extends Extension implements CertAttrSet {
 
     // Encode this extension value
     private void encodeThis() throws IOException {
-        DerOutputStream os = new DerOutputStream();
-
-        os.putIA5String(mComment);
-        // DerOutputStream tmp = new DerOutputStream();
-        // os.write(DerValue.tag_Sequence,tmp);
-        extensionValue = os.toByteArray();
+        try (DerOutputStream os = new DerOutputStream()) {
+            os.putIA5String(mComment);
+            // DerOutputStream tmp = new DerOutputStream();
+            // os.write(DerValue.tag_Sequence,tmp);
+            extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/NameConstraintsExtension.java b/base/util/src/netscape/security/x509/NameConstraintsExtension.java
index 87309080b4574534b84a117732b4f9513f40c40e..66145bf6793f15ee744de10909606d77fdeddad7 100644
--- a/base/util/src/netscape/security/x509/NameConstraintsExtension.java
+++ b/base/util/src/netscape/security/x509/NameConstraintsExtension.java
@@ -85,26 +85,29 @@ public class NameConstraintsExtension extends Extension implements CertAttrSet {
 
     // Encode this extension value.
     private void encodeThis() throws IOException {
-        DerOutputStream seq = new DerOutputStream();
+        try (DerOutputStream seq = new DerOutputStream()) {
 
-        DerOutputStream tagged = new DerOutputStream();
-        if ((permitted != null) && (permitted.getSubtrees().size() > 0)) {
-            DerOutputStream tmp = new DerOutputStream();
-            permitted.encode(tmp);
-            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                 true, TAG_PERMITTED), tmp);
-        }
-        if ((excluded != null) && (excluded.getSubtrees().size() > 0)) {
-            DerOutputStream tmp = new DerOutputStream();
-            excluded.encode(tmp);
-            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                 true, TAG_EXCLUDED), tmp);
-        }
-        if (permitted == null && excluded == null) {
-            extensionValue = null; // no need to encode this extension
-        } else {
-            seq.write(DerValue.tag_Sequence, tagged);
-            this.extensionValue = seq.toByteArray();
+            DerOutputStream tagged = new DerOutputStream();
+            if ((permitted != null) && (permitted.getSubtrees().size() > 0)) {
+                DerOutputStream tmp = new DerOutputStream();
+                permitted.encode(tmp);
+                tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+                        true, TAG_PERMITTED), tmp);
+            }
+            if ((excluded != null) && (excluded.getSubtrees().size() > 0)) {
+                DerOutputStream tmp = new DerOutputStream();
+                excluded.encode(tmp);
+                tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+                        true, TAG_EXCLUDED), tmp);
+            }
+            if (permitted == null && excluded == null) {
+                extensionValue = null; // no need to encode this extension
+            } else {
+                seq.write(DerValue.tag_Sequence, tagged);
+                this.extensionValue = seq.toByteArray();
+            }
+        } catch (IOException e) {
+            throw e;
         }
     }
 
diff --git a/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java b/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java
index abf46e42815ce30f3d7300d78f4e70f53ee8d927..4f034b4999c2dfc0a77241a5e7d5963770b2d3f3 100644
--- a/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java
+++ b/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java
@@ -79,23 +79,26 @@ public class PolicyConstraintsExtension extends Extension
 
     // Encode this extension value.
     private void encodeThis() throws IOException {
-        DerOutputStream tagged = new DerOutputStream();
-        DerOutputStream seq = new DerOutputStream();
+        try (DerOutputStream seq = new DerOutputStream()) {
+            DerOutputStream tagged = new DerOutputStream();
 
-        if (require != -1) {
-            DerOutputStream tmp = new DerOutputStream();
-            tmp.putInteger(new BigInt(require));
-            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                         false, TAG_REQUIRE), tmp);
+            if (require != -1) {
+                DerOutputStream tmp = new DerOutputStream();
+                tmp.putInteger(new BigInt(require));
+                tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+                        false, TAG_REQUIRE), tmp);
+            }
+            if (inhibit != -1) {
+                DerOutputStream tmp = new DerOutputStream();
+                tmp.putInteger(new BigInt(inhibit));
+                tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+                        false, TAG_INHIBIT), tmp);
+            }
+            seq.write(DerValue.tag_Sequence, tagged);
+            extensionValue = seq.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        if (inhibit != -1) {
-            DerOutputStream tmp = new DerOutputStream();
-            tmp.putInteger(new BigInt(inhibit));
-            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                         false, TAG_INHIBIT), tmp);
-        }
-        seq.write(DerValue.tag_Sequence, tagged);
-        extensionValue = seq.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/PolicyMappingsExtension.java b/base/util/src/netscape/security/x509/PolicyMappingsExtension.java
index 458e32d4a5bedc3594c5ee0b8bbb3a30b39bf317..35db8869d8f5a32c6affd64debfa87c7f1c25a3c 100644
--- a/base/util/src/netscape/security/x509/PolicyMappingsExtension.java
+++ b/base/util/src/netscape/security/x509/PolicyMappingsExtension.java
@@ -69,14 +69,17 @@ public class PolicyMappingsExtension extends Extension
 
     // Encode this extension value
     private void encodeThis() throws IOException {
-        DerOutputStream os = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream os = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        for (int i = 0; i < maps.size(); i++) {
-            maps.elementAt(i).encode(tmp);
+            for (int i = 0; i < maps.size(); i++) {
+                maps.elementAt(i).encode(tmp);
+            }
+            os.write(DerValue.tag_Sequence, tmp);
+            extensionValue = os.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        os.write(DerValue.tag_Sequence, tmp);
-        extensionValue = os.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java b/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java
index 80af3d1c41fcf5706d9c417c27bdce484fe48893..89e01981c7794fbe92e7cdf133b8d3bc43ad6dd5 100644
--- a/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java
+++ b/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java
@@ -81,23 +81,26 @@ public class PrivateKeyUsageExtension extends Extension
 
     // Encode this extension value.
     private void encodeThis() throws IOException {
-        DerOutputStream seq = new DerOutputStream();
+        try (DerOutputStream seq = new DerOutputStream()) {
 
-        DerOutputStream tagged = new DerOutputStream();
-        if (notBefore != null) {
-            DerOutputStream tmp = new DerOutputStream();
-            tmp.putGeneralizedTime(notBefore);
-            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                 false, TAG_BEFORE), tmp);
+            DerOutputStream tagged = new DerOutputStream();
+            if (notBefore != null) {
+                DerOutputStream tmp = new DerOutputStream();
+                tmp.putGeneralizedTime(notBefore);
+                tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+                        false, TAG_BEFORE), tmp);
+            }
+            if (notAfter != null) {
+                DerOutputStream tmp = new DerOutputStream();
+                tmp.putGeneralizedTime(notAfter);
+                tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+                        false, TAG_AFTER), tmp);
+            }
+            seq.write(DerValue.tag_Sequence, tagged);
+            extensionValue = seq.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-        if (notAfter != null) {
-            DerOutputStream tmp = new DerOutputStream();
-            tmp.putGeneralizedTime(notAfter);
-            tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
-                                 false, TAG_AFTER), tmp);
-        }
-        seq.write(DerValue.tag_Sequence, tagged);
-        extensionValue = seq.toByteArray();
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/RevokedCertImpl.java b/base/util/src/netscape/security/x509/RevokedCertImpl.java
index eac11f8e3f13e088cd8ebcc9c1e6e37c5772363c..a54c4471ab8bebd0ecf6d6da583f6b1b4695b6b6 100755
--- a/base/util/src/netscape/security/x509/RevokedCertImpl.java
+++ b/base/util/src/netscape/security/x509/RevokedCertImpl.java
@@ -225,7 +225,7 @@ public class RevokedCertImpl extends RevokedCertificate implements Serializable
      */
     public void encode(DerOutputStream outStrm) throws CRLException,
             X509ExtensionException {
-        try {
+        try (DerOutputStream seq = new DerOutputStream()) {
             if (revokedCert == null) {
                 DerOutputStream tmp = new DerOutputStream();
                 // sequence { serialNumber, revocationDate, extensions }
@@ -237,7 +237,6 @@ public class RevokedCertImpl extends RevokedCertificate implements Serializable
                 if (extensions != null)
                     extensions.encode(tmp, isExplicit);
 
-                DerOutputStream seq = new DerOutputStream();
                 seq.write(DerValue.tag_Sequence, tmp);
 
                 revokedCert = seq.toByteArray();
@@ -348,7 +347,7 @@ public class RevokedCertImpl extends RevokedCertificate implements Serializable
     public byte[] getExtensionValue(String oid) {
         if (extensions == null)
             return null;
-        try {
+        try (DerOutputStream out = new DerOutputStream()) {
             String extAlias = OIDMap.getName(new ObjectIdentifier(oid));
             Extension crlExt = null;
 
@@ -372,7 +371,6 @@ public class RevokedCertImpl extends RevokedCertificate implements Serializable
             if (extData == null)
                 return null;
 
-            DerOutputStream out = new DerOutputStream();
             out.putOctetString(extData);
             return out.toByteArray();
         } catch (Exception e) {
diff --git a/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java b/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java
index 42ef26aa932d3ce905f6ebee14511abd2721d451..7e3c2734fb98b125f7ad026ee511e2f244294582 100644
--- a/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java
+++ b/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java
@@ -81,18 +81,21 @@ public class SubjectDirAttributesExtension extends Extension
 
     // Encode this extension value
     private void encodeThis() throws IOException {
-        DerOutputStream out = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        //encoding the attributes
-        Enumeration<Attribute> attrs = attrList.elements();
-        while (attrs.hasMoreElements()) {
-            Attribute attr = attrs.nextElement();
-            attr.encode(tmp);
+            //encoding the attributes
+            Enumeration<Attribute> attrs = attrList.elements();
+            while (attrs.hasMoreElements()) {
+                Attribute attr = attrs.nextElement();
+                attr.encode(tmp);
+            }
+
+            out.write(DerValue.tag_SequenceOf, tmp);
+            this.extensionValue = out.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-
-        out.write(DerValue.tag_SequenceOf, tmp);
-        this.extensionValue = out.toByteArray();
     }
 
     // Decode this extension value
diff --git a/base/util/src/netscape/security/x509/X500Name.java b/base/util/src/netscape/security/x509/X500Name.java
index d0111a27e04e98a4db6a4ee44fc8324595678bf5..42cc8d829d5ae81d80eadb3e0cdb5408f1dfb8d5 100644
--- a/base/util/src/netscape/security/x509/X500Name.java
+++ b/base/util/src/netscape/security/x509/X500Name.java
@@ -591,23 +591,25 @@ public class X500Name implements Principal, GeneralNameInterface {
      *         null if no names are present.
      */
     public byte[] getEncoded() throws IOException {
+        try (DerOutputStream out = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        DerOutputStream out = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+            int len = 0;
 
-        int len = 0;
+            if (names == null) {
+                len = 0;
+            } else {
+                len = names.length;
+            }
 
-        if (names == null) {
-            len = 0;
-        } else {
-            len = names.length;
+            for (int i = 0; i < len; i++)
+                names[i].encode(tmp);
+
+            out.write(DerValue.tag_Sequence, tmp);
+            return out.toByteArray();
+        } catch (IOException e) {
+            throw e;
         }
-
-        for (int i = 0; i < len; i++)
-            names[i].encode(tmp);
-
-        out.write(DerValue.tag_Sequence, tmp);
-        return out.toByteArray();
     }
 
     /*
diff --git a/base/util/src/netscape/security/x509/X509CRLImpl.java b/base/util/src/netscape/security/x509/X509CRLImpl.java
index 843cba8e2a40746944d08cdaabaf16e867b18524..dfc1017bce80d02927c7c968e4b8d4c00b6285f1 100755
--- a/base/util/src/netscape/security/x509/X509CRLImpl.java
+++ b/base/util/src/netscape/security/x509/X509CRLImpl.java
@@ -326,10 +326,9 @@ public class X509CRLImpl extends X509CRL {
      */
     public void encodeInfo(OutputStream out)
             throws CRLException, X509ExtensionException {
-        try {
+        try (DerOutputStream seq = new DerOutputStream()) {
             DerOutputStream tmp = new DerOutputStream();
             DerOutputStream rCerts = new DerOutputStream();
-            DerOutputStream seq = new DerOutputStream();
 
             if (version != 0) // v2 crl encode version
                 tmp.putInteger(new BigInt(version));
@@ -476,7 +475,7 @@ public class X509CRLImpl extends X509CRL {
     public void sign(PrivateKey key, String algorithm, String provider)
             throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
             NoSuchProviderException, SignatureException, X509ExtensionException {
-        try {
+        try (DerOutputStream out = new DerOutputStream()){
             if (readOnly)
                 throw new CRLException("cannot over-write existing CRL");
             Signature sigEngine = null;
@@ -491,7 +490,6 @@ public class X509CRLImpl extends X509CRL {
             sigAlgId = AlgorithmId.get(sigEngine.getAlgorithm());
             infoSigAlgId = sigAlgId;
 
-            DerOutputStream out = new DerOutputStream();
             DerOutputStream tmp = new DerOutputStream();
 
             // encode crl info
@@ -848,7 +846,7 @@ public class X509CRLImpl extends X509CRL {
     public byte[] getExtensionValue(String oid) {
         if (extensions == null)
             return null;
-        try {
+        try (DerOutputStream out = new DerOutputStream()) {
             String extAlias = OIDMap.getName(new ObjectIdentifier(oid));
             Extension crlExt = null;
 
@@ -871,7 +869,7 @@ public class X509CRLImpl extends X509CRL {
             byte[] extData = crlExt.getExtensionValue();
             if (extData == null)
                 return null;
-            DerOutputStream out = new DerOutputStream();
+
             out.putOctetString(extData);
             return out.toByteArray();
         } catch (Exception e) {
diff --git a/base/util/src/netscape/security/x509/X509Cert.java b/base/util/src/netscape/security/x509/X509Cert.java
index 021cae2070580dd45ce2d290daebe59c8e9d37b3..351d4edf5dc14b0a0901302e5cf728ecf0687a93 100644
--- a/base/util/src/netscape/security/x509/X509Cert.java
+++ b/base/util/src/netscape/security/x509/X509Cert.java
@@ -805,24 +805,27 @@ public class X509Cert implements Certificate, Serializable {
          * Encode the to-be-signed data, then the algorithm used
          * to create the signature.
          */
-        DerOutputStream out = new DerOutputStream();
-        DerOutputStream tmp = new DerOutputStream();
+        try (DerOutputStream out = new DerOutputStream()) {
+            DerOutputStream tmp = new DerOutputStream();
 
-        tmp.write(data);
-        issuer.getAlgorithmId().encode(tmp);
+            tmp.write(data);
+            issuer.getAlgorithmId().encode(tmp);
 
-        /*
-         * Create and encode the signature itself.
-         */
-        issuer.update(data, 0, data.length);
-        signature = issuer.sign();
-        tmp.putBitString(signature);
+            /*
+             * Create and encode the signature itself.
+             */
+            issuer.update(data, 0, data.length);
+            signature = issuer.sign();
+            tmp.putBitString(signature);
 
-        /*
-         * Wrap the signed data in a SEQUENCE { data, algorithm, sig }
-         */
-        out.write(DerValue.tag_Sequence, tmp);
-        return out.toByteArray();
+            /*
+             * Wrap the signed data in a SEQUENCE { data, algorithm, sig }
+             */
+            out.write(DerValue.tag_Sequence, tmp);
+            return out.toByteArray();
+        } catch (IOException | SignatureException e) {
+            throw e;
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/X509CertImpl.java b/base/util/src/netscape/security/x509/X509CertImpl.java
index 2d24b66590c1957a09665e78c6382a69a8cfe797..111cd3b6d07c7118d28adb63594f1baafae1d08e 100755
--- a/base/util/src/netscape/security/x509/X509CertImpl.java
+++ b/base/util/src/netscape/security/x509/X509CertImpl.java
@@ -405,7 +405,7 @@ public class X509CertImpl extends X509Certificate
     public void sign(PrivateKey key, String algorithm, String provider)
             throws CertificateException, NoSuchAlgorithmException,
             InvalidKeyException, NoSuchProviderException, SignatureException {
-        try {
+        try (DerOutputStream out = new DerOutputStream()){
             if (readOnly)
                 throw new CertificateEncodingException(
                               "cannot over-write existing certificate");
@@ -420,7 +420,6 @@ public class X509CertImpl extends X509Certificate
             // in case the name is reset
             algId = AlgorithmId.get(sigEngine.getAlgorithm());
 
-            DerOutputStream out = new DerOutputStream();
             DerOutputStream tmp = new DerOutputStream();
 
             // encode certificate info
diff --git a/base/util/test/com/netscape/security/util/StringTestUtil.java b/base/util/test/com/netscape/security/util/StringTestUtil.java
index 16810581cbad55f7326025a250304cb1ade75538..1d25debc342d62695c616c651512bde2782c1eda 100644
--- a/base/util/test/com/netscape/security/util/StringTestUtil.java
+++ b/base/util/test/com/netscape/security/util/StringTestUtil.java
@@ -31,29 +31,35 @@ public class StringTestUtil {
 
     public static byte[] normalizeUnicode(byte[] data) throws Exception {
 
-        DerValue value = new DerValue(data);
-        byte[] tmp = value.data.toByteArray();
+        try (DerOutputStream os = new DerOutputStream()) {
+            DerValue value = new DerValue(data);
+            byte[] tmp = value.data.toByteArray();
 
-        if (tmp[0] == -2 && tmp[1] == -1) { // remove optional big-endian byte-order mark
+            if (tmp[0] == -2 && tmp[1] == -1) { // remove optional big-endian byte-order mark
 
-            byte tag = value.tag;
-            int length = value.length() - 2;
+                byte tag = value.tag;
+                int length = value.length() - 2;
 
-            DerOutputStream os = new DerOutputStream();
-            os.putTag((byte) 0, false, tag);
-            os.putLength(length);
-            os.write(tmp, 2, length);
+                os.putTag((byte) 0, false, tag);
+                os.putLength(length);
+                os.write(tmp, 2, length);
 
-            return os.toByteArray();
+                return os.toByteArray();
+            }
+
+            return data;
+        } catch (Exception e) {
+            throw e;
         }
-
-        return data;
     }
 
     public static byte[] encode(byte tag, String string) throws Exception {
-        DerOutputStream os = new DerOutputStream();
-        os.putStringType(tag, string);
-        return os.toByteArray();
+        try (DerOutputStream os = new DerOutputStream()) {
+            os.putStringType(tag, string);
+            return os.toByteArray();
+        } catch (Exception e) {
+            throw e;
+        }
     }
 
     public static String decode(byte tag, byte[] bytes) throws Exception {
-- 
1.8.1.2

