Don't inherit SafeHandle for C# prop-having class
authorKyungwook Tak <k.tak@samsung.com>
Tue, 8 Nov 2016 04:58:37 +0000 (13:58 +0900)
committerKyungwook Tak <k.tak@samsung.com>
Tue, 8 Nov 2016 07:56:01 +0000 (16:56 +0900)
Some classes who inherits SafeHandle have setter/getter by C# property
and their handle is not usable without checking property values.
So to maintain handle is meaningless and it can be converted just when
needed.

For CipherParameters class, it doesn't have setter/getter with C#
property so SafeHandle here is used properly and not removed.

Change-Id: Ib75edf5af74d4a0fbf44fbb7c16b836eee92a790
Signed-off-by: Kyungwook Tak <k.tak@samsung.com>
13 files changed:
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/Certificate.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/CertificateManager.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/Crypto/Cipher.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/Crypto/CipherParameters.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/Crypto/Signature.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/DataManager.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/Key.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/KeyManager.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/Pkcs12.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/Pkcs12Manager.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/SafeAliasListHandle.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/SafeCertificateListHandle.cs
Tizen.Security.SecureRepository/Tizen.Security.SecureRepository/SafeRawBufferHandle.cs

index f71bd14..5ffbe0b 100644 (file)
@@ -23,7 +23,7 @@ namespace Tizen.Security.SecureRepository
     /// <summary>
     /// Class that represents a certificate.
     /// </summary>
-    public class Certificate : SafeHandle
+    public class Certificate
     {
         /// <summary>
         /// Load Certificate from the given file path.
@@ -50,14 +50,13 @@ namespace Tizen.Security.SecureRepository
         /// </summary>
         /// <param name="binary">The binary data of a certificate.</param>
         /// <param name="format">The format of the binary data.</param>
-        public Certificate(byte[] binary, DataFormat format) : base(IntPtr.Zero, true)
+        public Certificate(byte[] binary, DataFormat format)
         {
             this.Binary = binary;
             this.Format = format;
         }
 
-        internal Certificate(IntPtr ptr, bool ownsHandle = true) :
-            base(ptr, ownsHandle)
+        internal Certificate(IntPtr ptr)
         {
             if (ptr == IntPtr.Zero)
                 throw new ArgumentNullException("Returned ptr from CAPI cannot be null");
@@ -70,23 +69,16 @@ namespace Tizen.Security.SecureRepository
 
         // Refresh handle(IntPtr) always. Because C# layer
         // properties(Binary, Format) could be changed.
-        internal IntPtr GetHandle(bool updateHandle = true)
+        internal IntPtr GetHandle()
         {
             IntPtr ptr = IntPtr.Zero;
             try
             {
-                int ret = CkmcTypes.CertNew(
-                    this.Binary, (UIntPtr)this.Binary.Length, (int)this.Format, out ptr);
-                CheckNThrowException(ret, "Failed to create cert");
-
-                if (updateHandle)
-                {
-                    if (!this.IsInvalid && !this.ReleaseHandle())
-                        throw new InvalidOperationException(
-                            "Failed to release cert handle");
-
-                    this.SetHandle(ptr);
-                }
+                CheckNThrowException(
+                    CkmcTypes.CertNew(
+                        this.Binary, (UIntPtr)this.Binary.Length, (int)this.Format,
+                        out ptr),
+                    "Failed to create cert");
 
                 return ptr;
             }
@@ -122,25 +114,5 @@ namespace Tizen.Security.SecureRepository
                 (Binary == null) ? 0 : this.Binary.Length,
                 (int)Format);
         }
-
-        /// <summary>
-        /// Gets a value that indicates whether the handle is invalid.
-        /// </summary>
-        public override bool IsInvalid
-        {
-            get { return this.handle == IntPtr.Zero; }
-        }
-
-        /// <summary>
-        /// When overridden in a derived class, executes the code required to free
-        /// the handle.
-        /// </summary>
-        /// <returns>true if the handle is released successfully.</returns>
-        protected override bool ReleaseHandle()
-        {
-            Interop.CkmcTypes.CertFree(this.handle);
-            this.SetHandle(IntPtr.Zero);
-            return true;
-        }
     }
 }
index c2b570b..dee27de 100644 (file)
@@ -16,6 +16,7 @@
 
 using System;
 using System.Collections.Generic;
+using static Interop;
 
 namespace Tizen.Security.SecureRepository
 {
@@ -38,12 +39,20 @@ namespace Tizen.Security.SecureRepository
         /// </exception>
         static public Certificate Get(string alias, string password)
         {
-            IntPtr ptr = new IntPtr();
+            IntPtr ptr = IntPtr.Zero;
 
-            int ret = Interop.CkmcManager.GetCert(alias, password, out ptr);
-            Interop.CheckNThrowException(ret, "Failed to get certificate. alias=" + alias);
-
-            return new Certificate(ptr);
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetCert(alias, password, out ptr),
+                    "Failed to get certificate. alias=" + alias);
+                return new Certificate(ptr);
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.CertFree(ptr);
+            }
         }
 
         /// <summary>
@@ -53,11 +62,20 @@ namespace Tizen.Security.SecureRepository
         /// <exception cref="ArgumentException">No alias to get.</exception>
         static public IEnumerable<string> GetAliases()
         {
-            IntPtr ptr = new IntPtr();
-            int ret = Interop.CkmcManager.GetCertAliasList(out ptr);
-            Interop.CheckNThrowException(ret, "Failed to get certificate aliases.");
+            IntPtr ptr = IntPtr.Zero;
 
-            return new SafeAliasListHandle(ptr).Aliases;
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetCertAliasList(out ptr),
+                    "Failed to get certificate aliases.");
+                return new SafeAliasListHandle(ptr).Aliases;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.AliasListAllFree(ptr);
+            }
         }
 
         /// <summary>
@@ -70,8 +88,10 @@ namespace Tizen.Security.SecureRepository
         /// <exception cref="InvalidOperationException">Certificate with alias does already exist.</exception>
         static public void Save(string alias, Certificate cert, Policy policy)
         {
-            int ret = Interop.CkmcManager.SaveCert(alias, cert.ToCkmcCert(), policy.ToCkmcPolicy());
-            Interop.CheckNThrowException(ret, "Failed to save certificate. alias=" + alias);
+            Interop.CheckNThrowException(
+                Interop.CkmcManager.SaveCert(
+                    alias, cert.ToCkmcCert(), policy.ToCkmcPolicy()),
+                "Failed to save certificate. alias=" + alias);
         }
 
         /// <summary>
@@ -91,16 +111,32 @@ namespace Tizen.Security.SecureRepository
         static public IEnumerable<Certificate> GetCertificateChain(Certificate certificate,
                                                                    IEnumerable<Certificate> untrustedCertificates)
         {
-            var ptrCertChain = new IntPtr();
-            var untrustedCerts = new SafeCertificateListHandle(untrustedCertificates);
+            IntPtr ptrCertChain = IntPtr.Zero;
+            IntPtr certPtr = IntPtr.Zero;
+            IntPtr untrustedPtr = IntPtr.Zero;
+
+            try
+            {
+                var untrusted = new SafeCertificateListHandle(untrustedCertificates);
+
+                certPtr = certificate.GetHandle();
+                untrustedPtr = untrusted.GetHandle();
 
-            int ret = Interop.CkmcManager.GetCertChain(certificate.GetHandle(),
-                                                       untrustedCerts.GetHandle(),
-                                                       out ptrCertChain);
-            Interop.CheckNThrowException(ret, "Failed to get certificate chain");
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetCertChain(
+                        certPtr, untrustedPtr,
+                        out ptrCertChain),
+                    "Failed to get certificate chain");
 
-            var certChain = new SafeCertificateListHandle(ptrCertChain);
-            return certChain.Certificates;
+                return new SafeCertificateListHandle(ptrCertChain).Certificates;
+            }
+            finally
+            {
+                if (certPtr != IntPtr.Zero)
+                    Interop.CkmcTypes.CertFree(certPtr);
+                if (untrustedPtr != IntPtr.Zero)
+                    Interop.CkmcTypes.CertListAllFree(untrustedPtr);
+            }
         }
 
         /// <summary>
@@ -123,19 +159,36 @@ namespace Tizen.Security.SecureRepository
                                                                    IEnumerable<Certificate> trustedCertificates,
                                                                    bool useTrustedSystemCertificates)
         {
-            var ptrCertChain = new IntPtr();
-            var untrustedCerts = new SafeCertificateListHandle(untrustedCertificates);
-            var trustedCerts = new SafeCertificateListHandle(trustedCertificates);
+            IntPtr certPtr = IntPtr.Zero;
+            IntPtr untrustedPtr = IntPtr.Zero;
+            IntPtr trustedPtr = IntPtr.Zero;
+            IntPtr ptrCertChain = IntPtr.Zero;
 
-            int ret = Interop.CkmcManager.GetCertChainWithTrustedCerts(
-                            certificate.GetHandle(), untrustedCerts.GetHandle(),
-                            trustedCerts.GetHandle(), useTrustedSystemCertificates,
-                            out ptrCertChain);
-            Interop.CheckNThrowException(ret, "Failed to get certificate chain with trusted certificates");
+            try
+            {
+                var untrusted = new SafeCertificateListHandle(untrustedCertificates);
+                var trusted = new SafeCertificateListHandle(trustedCertificates);
 
-            var certChain = new SafeCertificateListHandle(ptrCertChain);
+                certPtr = certificate.GetHandle();
+                untrustedPtr = untrusted.GetHandle();
+                trustedPtr = trusted.GetHandle();
 
-            return certChain.Certificates;
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetCertChainWithTrustedCerts(
+                        certPtr, untrustedPtr, trustedPtr,
+                        useTrustedSystemCertificates, out ptrCertChain),
+                    "Failed to get certificate chain with trusted certificates");
+                return new SafeCertificateListHandle(ptrCertChain).Certificates;
+            }
+            finally
+            {
+                if (certPtr != IntPtr.Zero)
+                    Interop.CkmcTypes.CertFree(certPtr);
+                if (untrustedPtr != IntPtr.Zero)
+                    Interop.CkmcTypes.CertListAllFree(untrustedPtr);
+                if (trustedPtr != IntPtr.Zero)
+                    Interop.CkmcTypes.CertListAllFree(trustedPtr);
+            }
         }
 
         /// <summary>
@@ -147,11 +200,25 @@ namespace Tizen.Security.SecureRepository
         /// <exception cref="InvalidOperationException">some of certificate in chain is expired or not valid yet.</exception>
         static public OcspStatus CheckOcsp(IEnumerable<Certificate> certificateChain)
         {
-            int ocspStatus = (int)OcspStatus.Good;
-            SafeCertificateListHandle certChain = new SafeCertificateListHandle(certificateChain);
-            int ret = Interop.CkmcManager.OcspCheck(certChain.GetHandle(), ref ocspStatus);
-            Interop.CheckNThrowException(ret, "Failed to get certificate chain with trusted certificates");
-            return (OcspStatus)ocspStatus;
+            IntPtr ptr = IntPtr.Zero;
+
+            try
+            {
+                int ocspStatus = (int)OcspStatus.Good;
+                var certChain = new SafeCertificateListHandle(certificateChain);
+
+                ptr = certChain.GetHandle();
+
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.OcspCheck(ptr, ref ocspStatus),
+                    "Failed to get certificate chain with trusted certificates");
+                return (OcspStatus)ocspStatus;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.CertListAllFree(ptr);
+            }
         }
     }
 }
index f051e6c..4d11b46 100644 (file)
@@ -62,13 +62,24 @@ namespace Tizen.Security.SecureRepository.Crypto
         /// <remarks>The key type specified by keyAlias should be compatible with the algorithm specified in Parameters.</remarks>
         public byte[] Decrypt(string keyAlias, string password, byte[] cipherText)
         {
-            IntPtr ptrPlainText = new IntPtr();
-            Interop.CkmcRawBuffer cipherTextBuff = new Interop.CkmcRawBuffer(new PinnedObject(cipherText), cipherText.Length);
+            IntPtr ptr = IntPtr.Zero;
 
-            int ret = Interop.CkmcManager.DecryptData(Parameters.PtrCkmcParamList, keyAlias, password, cipherTextBuff, out ptrPlainText);
-            Interop.CheckNThrowException(ret, "Failed to decrypt data");
-
-            return new SafeRawBufferHandle(ptrPlainText).Data;
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.DecryptData(
+                        Parameters.PtrCkmcParamList, keyAlias, password,
+                        new Interop.CkmcRawBuffer(
+                            new PinnedObject(cipherText), cipherText.Length),
+                        out ptr),
+                    "Failed to decrypt data");
+                return new SafeRawBufferHandle(ptr).Data;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.BufferFree(ptr);
+            }
         }
 
         /// <summary>
@@ -92,13 +103,24 @@ namespace Tizen.Security.SecureRepository.Crypto
         /// <remarks>The key type specified by keyAlias should be compatible with the algorithm specified in Parameters.</remarks>
         public byte[] Encrypt(string keyAlias, string password, byte[] plainText)
         {
-            IntPtr ptrCipherText = new IntPtr();
-            Interop.CkmcRawBuffer plainTextBuff = new Interop.CkmcRawBuffer(new PinnedObject(plainText), plainText.Length);
-
-            int ret = Interop.CkmcManager.EncryptData(Parameters.PtrCkmcParamList, keyAlias, password, plainTextBuff, out ptrCipherText);
-            Interop.CheckNThrowException(ret, "Failed to encrypt data");
+            IntPtr ptr = IntPtr.Zero;
 
-            return new SafeRawBufferHandle(ptrCipherText).Data;
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.EncryptData(
+                        Parameters.PtrCkmcParamList, keyAlias, password,
+                        new Interop.CkmcRawBuffer(
+                            new PinnedObject(plainText), plainText.Length),
+                        out ptr),
+                    "Failed to encrypt data");
+                return new SafeRawBufferHandle(ptr).Data;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.BufferFree(ptr);
+            }
         }
     }
 }
index 823a774..5157cb3 100644 (file)
@@ -95,12 +95,21 @@ namespace Tizen.Security.SecureRepository.Crypto
         /// </exception>
         public byte[] GetBuffer(CipherParameterName name)
         {
-            IntPtr ptr = new IntPtr();
+            IntPtr ptr = IntPtr.Zero;
 
-            int ret = Interop.CkmcTypes.ParamListGetBuffer(PtrCkmcParamList, (int)name, out ptr);
-            Interop.CheckNThrowException(ret, "Failed to get parameter.");
-
-            return new SafeRawBufferHandle(ptr).Data;
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcTypes.ParamListGetBuffer(
+                        PtrCkmcParamList, (int)name, out ptr),
+                    "Failed to get parameter.");
+                return new SafeRawBufferHandle(ptr).Data;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.BufferFree(ptr);
+            }
         }
 
         /// <summary>
@@ -113,7 +122,7 @@ namespace Tizen.Security.SecureRepository.Crypto
 
         internal IntPtr PtrCkmcParamList
         {
-            get { return handle; }
+            get { return this.handle; }
         }
 
         /// <summary>
@@ -121,7 +130,7 @@ namespace Tizen.Security.SecureRepository.Crypto
         /// </summary>
         public override bool IsInvalid
         {
-            get { return handle == IntPtr.Zero; }
+            get { return this.handle == IntPtr.Zero; }
         }
 
         /// <summary>
@@ -130,9 +139,7 @@ namespace Tizen.Security.SecureRepository.Crypto
         /// <returns>true if the handle is released successfully</returns>
         protected override bool ReleaseHandle()
         {
-            if (IsInvalid) // do not release
-                return true;
-            Interop.CkmcTypes.ParamListFree(handle);
+            Interop.CkmcTypes.ParamListFree(this.handle);
             this.SetHandle(IntPtr.Zero);
             return true;
         }
index b2b1108..eb42ab0 100644 (file)
@@ -72,14 +72,24 @@ namespace Tizen.Security.SecureRepository.Crypto
             }
             catch { }
 
-            IntPtr ptrSignature = new IntPtr();
-            Interop.CkmcRawBuffer messageBuff = new Interop.CkmcRawBuffer(new PinnedObject(message), message.Length);
+            IntPtr ptr = IntPtr.Zero;
 
-            int ret = Interop.CkmcManager.CreateSignature(privateKeyAlias, password, messageBuff,
-                                                            hash, rsaPadding, out ptrSignature);
-            Interop.CheckNThrowException(ret, "Failed to generate signature");
-
-            return new SafeRawBufferHandle(ptrSignature).Data;
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.CreateSignature(
+                        privateKeyAlias, password,
+                        new Interop.CkmcRawBuffer(
+                            new PinnedObject(message), message.Length),
+                        hash, rsaPadding, out ptr),
+                    "Failed to generate signature");
+                return new SafeRawBufferHandle(ptr).Data;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.BufferFree(ptr);
+            }
         }
 
         /// <summary>
@@ -113,11 +123,15 @@ namespace Tizen.Security.SecureRepository.Crypto
             }
             catch { }
 
-            Interop.CkmcRawBuffer messageBuff = new Interop.CkmcRawBuffer(new PinnedObject(message), message.Length);
-            Interop.CkmcRawBuffer signatureBuff = new Interop.CkmcRawBuffer(new PinnedObject(signature), signature.Length);
 
-            int ret = Interop.CkmcManager.VerifySignature(publicKeyAlias, password, messageBuff,
-                                                        signatureBuff, hash, rsaPadding);
+            int ret = Interop.CkmcManager.VerifySignature(
+                publicKeyAlias,
+                password,
+                new Interop.CkmcRawBuffer(new PinnedObject(message), message.Length),
+                new Interop.CkmcRawBuffer(new PinnedObject(signature), signature.Length),
+                hash,
+                rsaPadding);
+
             if (ret == (int)Interop.KeyManagerError.VerificationFailed)
                 return false;
             Interop.CheckNThrowException(ret, "Failed to verify signature");
index 8b112c3..bbd13fc 100644 (file)
@@ -16,6 +16,7 @@
 
 using System;
 using System.Collections.Generic;
+using static Interop;
 
 namespace Tizen.Security.SecureRepository
 {
@@ -38,12 +39,20 @@ namespace Tizen.Security.SecureRepository
         /// </exception>
         static public byte[] Get(string alias, string password)
         {
-            IntPtr ptr = new IntPtr();
+            IntPtr ptr = IntPtr.Zero;
 
-            int ret = Interop.CkmcManager.GetData(alias, password, out ptr);
-            Interop.CheckNThrowException(ret, "Failed to get certificate. alias=" + alias);
-
-            return new SafeRawBufferHandle(ptr).Data;
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetData(alias, password, out ptr),
+                    "Failed to get certificate. alias=" + alias);
+                return new SafeRawBufferHandle(ptr).Data;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.BufferFree(ptr);
+            }
         }
 
         /// <summary>
@@ -53,11 +62,20 @@ namespace Tizen.Security.SecureRepository
         /// <exception cref="ArgumentException">No alias to get.</exception>
         static public IEnumerable<string> GetAliases()
         {
-            IntPtr ptr = new IntPtr();
-            int ret = Interop.CkmcManager.GetDataAliasList(out ptr);
-            Interop.CheckNThrowException(ret, "Failed to get data aliases");
+            IntPtr ptr = IntPtr.Zero;
 
-            return new SafeAliasListHandle(ptr).Aliases;
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetDataAliasList(out ptr),
+                    "Failed to get data aliases");
+                return new SafeAliasListHandle(ptr).Aliases;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.AliasListAllFree(ptr);
+            }
         }
 
         /// <summary>
@@ -70,10 +88,12 @@ namespace Tizen.Security.SecureRepository
         /// <exception cref="InvalidOperationException">Data with alias does already exist.</exception>
         static public void Save(string alias, byte[] data, Policy policy)
         {
-            Interop.CkmcRawBuffer rawBuff = new Interop.CkmcRawBuffer(new PinnedObject(data), data.Length);
-
-            int ret = Interop.CkmcManager.SaveData(alias, rawBuff, policy.ToCkmcPolicy());
-            Interop.CheckNThrowException(ret, "Failed to save data. alias=" + alias);
+            Interop.CheckNThrowException(
+                Interop.CkmcManager.SaveData(
+                    alias,
+                    new Interop.CkmcRawBuffer(new PinnedObject(data), data.Length),
+                    policy.ToCkmcPolicy()),
+                "Failed to save data. alias=" + alias);
         }
     }
 }
index 6da8479..0ea7edd 100644 (file)
@@ -23,7 +23,7 @@ namespace Tizen.Security.SecureRepository
     /// <summary>
     /// Class that represents a key.
     /// </summary>
-    public class Key : SafeHandle
+    public class Key
     {
         /// <summary>
         /// A constructor of Key that takes the binary, its type, and optional password
@@ -36,15 +36,14 @@ namespace Tizen.Security.SecureRepository
         /// <param name="binaryPassword">
         /// The password used to decrypt binary when binary is encrypted.
         /// </param>
-        public Key(byte[] binary, KeyType type, string binaryPassword) :
-            base(IntPtr.Zero, true)
+        public Key(byte[] binary, KeyType type, string binaryPassword)
         {
             this.Binary = binary;
             this.Type = type;
             this.BinaryPassword = binaryPassword;
         }
 
-        internal Key(IntPtr ptr, bool ownsHandle = true) : base(ptr, ownsHandle)
+        internal Key(IntPtr ptr)
         {
             if (ptr == IntPtr.Zero)
                 throw new ArgumentNullException("Returned ptr from CAPI cannot be null");
@@ -58,24 +57,16 @@ namespace Tizen.Security.SecureRepository
 
         // Refresh handle(IntPtr) always. Because C# layer
         // properties(Binary, Type, BinaryPassword) could be changed.
-        internal IntPtr GetHandle(bool updateHandle = true)
+        internal IntPtr GetHandle()
         {
             IntPtr ptr = IntPtr.Zero;
             try
             {
-                int ret = Interop.CkmcTypes.KeyNew(
-                    this.Binary, (UIntPtr)this.Binary.Length, (int)this.Type,
-                    this.BinaryPassword, out ptr);
-                CheckNThrowException(ret, "Failed to create key");
-
-                if (updateHandle)
-                {
-                    if (!this.IsInvalid && !this.ReleaseHandle())
-                        throw new InvalidOperationException(
-                            "Failed to release key handle");
-
-                    this.SetHandle(ptr);
-                }
+                CheckNThrowException(
+                    Interop.CkmcTypes.KeyNew(
+                        this.Binary, (UIntPtr)this.Binary.Length, (int)this.Type,
+                        this.BinaryPassword, out ptr),
+                    "Failed to create key");
 
                 return ptr;
             }
@@ -120,25 +111,5 @@ namespace Tizen.Security.SecureRepository
                 (int)this.Type,
                 this.BinaryPassword);
         }
-
-        /// <summary>
-        /// Gets a value that indicates whether the handle is invalid.
-        /// </summary>
-        public override bool IsInvalid
-        {
-            get { return this.handle == IntPtr.Zero; }
-        }
-
-        /// <summary>
-        /// When overridden in a derived class, executes the code required to free
-        /// the handle.
-        /// </summary>
-        /// <returns>true if the handle is released successfully</returns>
-        protected override bool ReleaseHandle()
-        {
-            Interop.CkmcTypes.KeyFree(this.handle);
-            this.SetHandle(IntPtr.Zero);
-            return true;
-        }
     }
 }
index bf3ab41..58e19b7 100644 (file)
@@ -39,12 +39,20 @@ namespace Tizen.Security.SecureRepository
         /// </exception>
         static public Key Get(string alias, string password)
         {
-            IntPtr ptr = new IntPtr();
+            IntPtr ptr = IntPtr.Zero;
 
-            int ret = Interop.CkmcManager.GetKey(alias, password, out ptr);
-            Interop.CheckNThrowException(ret, "Failed to get key. alias=" + alias);
-
-            return new Key(ptr);
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetKey(alias, password, out ptr),
+                    "Failed to get key. alias=" + alias);
+                return new Key(ptr);
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.KeyFree(ptr);
+            }
         }
 
         /// <summary>
@@ -54,11 +62,20 @@ namespace Tizen.Security.SecureRepository
         /// <exception cref="ArgumentException">No alias to get.</exception>
         static public IEnumerable<string> GetAliases()
         {
-            IntPtr ptr = new IntPtr();
-            int ret = Interop.CkmcManager.GetKeyAliasList(out ptr);
-            Interop.CheckNThrowException(ret, "Failed to get key aliases.");
+            IntPtr ptr = IntPtr.Zero;
 
-            return new SafeAliasListHandle(ptr).Aliases;
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetKeyAliasList(out ptr),
+                    "Failed to get key aliases.");
+                return new SafeAliasListHandle(ptr).Aliases;
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.AliasListAllFree(ptr);
+            }
         }
 
         /// <summary>
index 27ecf2f..4719a00 100644 (file)
@@ -25,7 +25,7 @@ namespace Tizen.Security.SecureRepository
     /// Class that represents a PKCS#12 contents.
     /// It has a private key or its certificate or all the members of a chain of trust.
     /// </summary>
-    public class Pkcs12 : SafeHandle
+    public class Pkcs12
     {
         private SafeCertificateListHandle _certChainHandle = null;
 
@@ -46,17 +46,25 @@ namespace Tizen.Security.SecureRepository
         {
             IntPtr ptr = IntPtr.Zero;
 
-            int ret = Interop.CkmcTypes.Pkcs12Load(filePath, filePassword, out ptr);
-            Interop.CheckNThrowException(ret, "Failed to load PKCS12. file=" + filePath);
-
-            return new Pkcs12(ptr);
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcTypes.Pkcs12Load(filePath, filePassword, out ptr),
+                    "Failed to load PKCS12. file=" + filePath);
+                return new Pkcs12(ptr);
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.Pkcs12Free(ptr);
+            }
         }
 
         /// <summary>
         /// A constructor of Key that takes a private key.
         /// </summary>
         /// <param name="privateKey">A private key.</param>
-        public Pkcs12(Key privateKey) : base(IntPtr.Zero, true)
+        public Pkcs12(Key privateKey)
         {
             this.PrivateKey = privateKey;
             this.Certificate = null;
@@ -74,23 +82,22 @@ namespace Tizen.Security.SecureRepository
         /// </param>
         public Pkcs12(Key privateKey,
                       Certificate certificate,
-                      IEnumerable<Certificate> caChain) : base(IntPtr.Zero, true)
+                      IEnumerable<Certificate> caChain)
         {
             this.PrivateKey = privateKey;
             this.Certificate = certificate;
             this.CaChain = caChain;
         }
 
-        internal Pkcs12(IntPtr ptr, bool ownsHandle = true) : base(ptr, ownsHandle)
+        internal Pkcs12(IntPtr ptr)
         {
             var ckmcPkcs12 = Marshal.PtrToStructure<Interop.CkmcPkcs12>(ptr);
 
-            this.PrivateKey = new Key(ckmcPkcs12.privateKey, false);
+            this.PrivateKey = new Key(ckmcPkcs12.privateKey);
             if (ckmcPkcs12.certificate != IntPtr.Zero)
-                this.Certificate = new Certificate(ckmcPkcs12.certificate, false);
+                this.Certificate = new Certificate(ckmcPkcs12.certificate);
             if (ckmcPkcs12.caChain != IntPtr.Zero)
-                this._certChainHandle = new SafeCertificateListHandle(ckmcPkcs12.caChain,
-                                                                      false);
+                this._certChainHandle = new SafeCertificateListHandle(ckmcPkcs12.caChain);
         }
 
         internal IntPtr GetHandle()
@@ -101,23 +108,19 @@ namespace Tizen.Security.SecureRepository
             IntPtr p12Ptr = IntPtr.Zero;
             try
             {
-                keyPtr = this.PrivateKey.GetHandle(false);
+                keyPtr = this.PrivateKey.GetHandle();
 
                 if (this.Certificate != null)
-                    certPtr = this.Certificate.GetHandle(false);
+                    certPtr = this.Certificate.GetHandle();
 
                 if (this._certChainHandle != null)
-                    cacertPtr = this._certChainHandle.GetHandle(false);
+                    cacertPtr = this._certChainHandle.GetHandle();
 
                 Interop.CheckNThrowException(
                     Interop.CkmcTypes.Pkcs12New(keyPtr, certPtr, cacertPtr, out p12Ptr),
                     "Failed to create pkcs12");
 
-                if (!this.IsInvalid && !this.ReleaseHandle())
-                    throw new InvalidOperationException("Failed to release p12 handle");
-
-                this.SetHandle(p12Ptr);
-                return this.handle;
+                return p12Ptr;
             }
             catch
             {
@@ -175,25 +178,5 @@ namespace Tizen.Security.SecureRepository
                     this._certChainHandle = new SafeCertificateListHandle(value);
             }
         }
-
-        /// <summary>
-        /// Gets a value that indicates whether the handle is invalid.
-        /// </summary>
-        public override bool IsInvalid
-        {
-            get { return this.handle == IntPtr.Zero; }
-        }
-
-        /// <summary>
-        /// When overridden in a derived class, executes the code required to free
-        /// the handle.
-        /// </summary>
-        /// <returns>true if the handle is released successfully</returns>
-        protected override bool ReleaseHandle()
-        {
-            Interop.CkmcTypes.Pkcs12Free(this.handle);
-            this.SetHandle(IntPtr.Zero);
-            return true;
-        }
     }
 }
index 8241e3a..41b1572 100644 (file)
@@ -15,6 +15,7 @@
  */
 
 using System;
+using static Interop;
 
 namespace Tizen.Security.SecureRepository
 {
@@ -42,12 +43,21 @@ namespace Tizen.Security.SecureRepository
         /// </exception>
         static public Pkcs12 Get(string alias, string keyPassword, string cerificatePassword)
         {
-            IntPtr ptr = new IntPtr();
+            IntPtr ptr = IntPtr.Zero;
 
-            int ret = Interop.CkmcManager.GetPkcs12(alias, keyPassword, cerificatePassword, out ptr);
-            Interop.CheckNThrowException(ret, "Failed to get PKCS12. alias=" + alias);
-
-            return new Pkcs12(ptr);
+            try
+            {
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.GetPkcs12(
+                        alias, keyPassword, cerificatePassword, out ptr),
+                    "Failed to get PKCS12. alias=" + alias);
+                return new Pkcs12(ptr);
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.Pkcs12Free(ptr);
+            }
         }
 
         /// <summary>
@@ -62,11 +72,22 @@ namespace Tizen.Security.SecureRepository
         /// <exception cref="InvalidOperationException">Pkcs12 with alias does already exist.</exception>
         static public void Save(string alias, Pkcs12 pkcs12, Policy keyPolicy, Policy certificatePolicy)
         {
-            int ret = Interop.CkmcManager.SavePkcs12(alias,
-                                                     pkcs12.GetHandle(),
-                                                     keyPolicy.ToCkmcPolicy(),
-                                                     certificatePolicy.ToCkmcPolicy());
-            Interop.CheckNThrowException(ret, "Failed to save PKCS12. alias=" + alias);
+            IntPtr ptr = IntPtr.Zero;
+            try
+            {
+                ptr = pkcs12.GetHandle();
+
+                Interop.CheckNThrowException(
+                    Interop.CkmcManager.SavePkcs12(
+                        alias, ptr, keyPolicy.ToCkmcPolicy(),
+                        certificatePolicy.ToCkmcPolicy()),
+                    "Failed to save PKCS12. alias=" + alias);
+            }
+            finally
+            {
+                if (ptr != IntPtr.Zero)
+                    Interop.CkmcTypes.Pkcs12Free(ptr);
+            }
         }
     }
 }
index fa93b97..13c15d6 100644 (file)
@@ -21,16 +21,15 @@ using static Interop;
 
 namespace Tizen.Security.SecureRepository
 {
-    internal class SafeAliasListHandle : SafeHandle
+    internal class SafeAliasListHandle
     {
-        public SafeAliasListHandle(IntPtr ptr, bool ownsHandle = true) :
-            base(ptr, ownsHandle)
+        public SafeAliasListHandle(IntPtr ptr)
         {
             var cur = ptr;
             var aliases = new List<string>();
             while (cur != IntPtr.Zero)
             {
-                var ckmcAliasList = Marshal.PtrToStructure<CkmcAliasList>(cur);
+                var ckmcAliasList = Marshal.PtrToStructure<Interop.CkmcAliasList>(cur);
                 aliases.Add(Marshal.PtrToStringAnsi(ckmcAliasList.alias));
                 cur = ckmcAliasList.next;
             }
@@ -42,25 +41,5 @@ namespace Tizen.Security.SecureRepository
         {
             get; set;
         }
-
-        /// <summary>
-        /// Gets a value that indicates whether the handle is invalid.
-        /// </summary>
-        public override bool IsInvalid
-        {
-            get { return this.handle == IntPtr.Zero; }
-        }
-
-        /// <summary>
-        /// When overridden in a derived class, executes the code required to free
-        /// the handle.
-        /// </summary>
-        /// <returns>true if the handle is released successfully</returns>
-        protected override bool ReleaseHandle()
-        {
-            Interop.CkmcTypes.AliasListAllFree(this.handle);
-            this.SetHandle(IntPtr.Zero);
-            return true;
-        }
     }
 }
index 94412d5..7b1f75a 100644 (file)
@@ -21,25 +21,23 @@ using static Interop;
 
 namespace Tizen.Security.SecureRepository
 {
-    internal class SafeCertificateListHandle : SafeHandle
+    internal class SafeCertificateListHandle
     {
         private IEnumerable<Certificate> _certificates;
 
-        public SafeCertificateListHandle(IEnumerable<Certificate> certs) :
-            base(IntPtr.Zero, true)
+        public SafeCertificateListHandle(IEnumerable<Certificate> certs)
         {
             _certificates = certs;
         }
 
-        public SafeCertificateListHandle(IntPtr ptr, bool ownsHandle = true) :
-            base(ptr, ownsHandle)
+        public SafeCertificateListHandle(IntPtr ptr)
         {
             var cur = ptr;
             var certs = new List<Certificate>();
             while (cur != IntPtr.Zero)
             {
                 var ckmcCertList = Marshal.PtrToStructure<CkmcCertList>(cur);
-                certs.Add(new Certificate(ckmcCertList.cert, false));
+                certs.Add(new Certificate(ckmcCertList.cert));
                 cur = ckmcCertList.next;
             }
 
@@ -51,14 +49,11 @@ namespace Tizen.Security.SecureRepository
             get { return _certificates; }
         }
 
-        internal IntPtr GetHandle(bool updateHandle = true)
+        internal IntPtr GetHandle()
         {
             if (_certificates == null)
                 return IntPtr.Zero;
 
-            if (!IsInvalid)
-                return this.handle;
-
             IntPtr first = IntPtr.Zero;
             IntPtr previous = IntPtr.Zero;
             IntPtr certPtr = IntPtr.Zero;
@@ -71,7 +66,7 @@ namespace Tizen.Security.SecureRepository
                     // in case of exception occured
                     certPtr = IntPtr.Zero;
 
-                    certPtr = cert.GetHandle(false);
+                    certPtr = cert.GetHandle();
 
                     IntPtr outCertList;
                     if (previous == IntPtr.Zero)
@@ -91,40 +86,17 @@ namespace Tizen.Security.SecureRepository
                     previous = outCertList;
                 }
 
-                if (updateHandle)
-                    this.SetHandle(first);
-
                 return first;
             }
             catch
             {
                 if (first != IntPtr.Zero)
-                    Interop.CkmcTypes.CertListAllFree(this.handle);
+                    Interop.CkmcTypes.CertListAllFree(first);
                 if (certPtr != IntPtr.Zero)
                     Interop.CkmcTypes.CertFree(certPtr);
 
                 throw;
             }
         }
-
-        /// <summary>
-        /// Gets a value that indicates whether the handle is invalid.
-        /// </summary>
-        public override bool IsInvalid
-        {
-            get { return this.handle == IntPtr.Zero; }
-        }
-
-        /// <summary>
-        /// When overridden in a derived class, executes the code required to free
-        /// the handle.
-        /// </summary>
-        /// <returns>true if the handle is released successfully</returns>
-        protected override bool ReleaseHandle()
-        {
-            Interop.CkmcTypes.CertListAllFree(this.handle);
-            this.SetHandle(IntPtr.Zero);
-            return true;
-        }
     }
 }
index d558ba1..04c0db6 100644 (file)
@@ -20,10 +20,9 @@ using static Interop;
 
 namespace Tizen.Security.SecureRepository
 {
-    internal class SafeRawBufferHandle : SafeHandle
+    internal class SafeRawBufferHandle
     {
-        public SafeRawBufferHandle(IntPtr ptr, bool ownsHandle = true) :
-            base(ptr, true)
+        public SafeRawBufferHandle(IntPtr ptr)
         {
             if (ptr == IntPtr.Zero)
                 throw new ArgumentNullException("Returned ptr from CAPI cannot be null");
@@ -39,15 +38,12 @@ namespace Tizen.Security.SecureRepository
             IntPtr ptr = IntPtr.Zero;
             try
             {
-                int ret = Interop.CkmcTypes.BufferNew(
-                    this.Data, (UIntPtr)this.Data.Length, out ptr);
-                CheckNThrowException(ret, "Failed to create buf");
+                CheckNThrowException(
+                    Interop.CkmcTypes.BufferNew(
+                        this.Data, (UIntPtr)this.Data.Length, out ptr),
+                    "Failed to create buf");
 
-                if (!this.IsInvalid && !this.ReleaseHandle())
-                    throw new InvalidOperationException("Failed to release buf handle");
-
-                this.SetHandle(ptr);
-                return this.handle;
+                return ptr;
             }
             catch
             {
@@ -62,25 +58,5 @@ namespace Tizen.Security.SecureRepository
         {
             get; set;
         }
-
-        /// <summary>
-        /// Gets a value that indicates whether the handle is invalid.
-        /// </summary>
-        public override bool IsInvalid
-        {
-            get { return this.handle == IntPtr.Zero; }
-        }
-
-        /// <summary>
-        /// When overridden in a derived class, executes the code required to free
-        /// the handle.
-        /// </summary>
-        /// <returns>true if the handle is released successfully</returns>
-        protected override bool ReleaseHandle()
-        {
-            Interop.CkmcTypes.BufferFree(this.handle);
-            this.SetHandle(IntPtr.Zero);
-            return true;
-        }
     }
 }