From b631a675329428c19992b695dc6081c5654fa877 Mon Sep 17 00:00:00 2001 From: Kevin Jones Date: Wed, 28 Sep 2022 21:59:00 -0400 Subject: [PATCH] Dispose of key when importing X.509 certificate from PEM --- .../X509Certificates/X509Certificate2.cs | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs index 422c29c10e8f67..b2855084370f44 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs @@ -1433,16 +1433,18 @@ private static X509Certificate2 ExtractKeyFromPem( { if (label.SequenceEqual(eligibleLabel)) { - TAlg key = factory(); - key.ImportFromPem(contents[fields.Location]); - - try - { - return import(key); - } - catch (ArgumentException ae) + using (TAlg key = factory()) { - throw new CryptographicException(SR.Cryptography_X509_NoOrMismatchedPemKey, ae); + key.ImportFromPem(contents[fields.Location]); + + try + { + return import(key); + } + catch (ArgumentException ae) + { + throw new CryptographicException(SR.Cryptography_X509_NoOrMismatchedPemKey, ae); + } } } }