2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
18 using System.Collections.Generic;
19 using System.Runtime.InteropServices;
22 namespace Tizen.Security.SecureRepository
24 internal class SafeCertificateListHandle : SafeHandle
26 private IEnumerable<Certificate> _certificates;
28 public SafeCertificateListHandle(IEnumerable<Certificate> certs) : base(IntPtr.Zero, true)
30 this.SetHandle(IntPtr.Zero);
31 _certificates = certs;
34 public SafeCertificateListHandle(IntPtr ptrCerts, bool ownsHandle = true) : base(IntPtr.Zero, ownsHandle)
36 this.SetHandle(ptrCerts);
38 List<Certificate> certs = new List<Certificate>();
39 IntPtr ptrCurr = handle;
40 while (ptrCurr != IntPtr.Zero)
42 CkmcCertList ckmcCertList = (CkmcCertList)Marshal.PtrToStructure(ptrCurr, typeof(CkmcCertList));
43 certs.Add(new Certificate(ckmcCertList.cert, false));
44 ptrCurr = ckmcCertList.next;
47 _certificates = certs;
50 public IEnumerable<Certificate> Certificates
52 get { return _certificates; }
55 internal IntPtr ToCkmcCertificateListPtr()
57 if (_certificates == null)
63 IntPtr first = IntPtr.Zero;
64 IntPtr previous = IntPtr.Zero;
67 foreach (Certificate cert in _certificates)
70 ret = Interop.CkmcTypes.CertNew(cert.Binary, (uint)cert.Binary.Length, (int)cert.Format, out certPtr);
71 Interop.CheckNThrowException(ret, "Failed to create new Certificate.");
74 if (previous == IntPtr.Zero)
76 ret = Interop.CkmcTypes.CertListNew(certPtr, out outCertList);
77 Interop.CheckNThrowException(ret, "Failed to create new CertificateList.");
79 previous = outCertList;
83 ret = Interop.CkmcTypes.CertListAdd(previous, certPtr, out outCertList);
84 Interop.CheckNThrowException(ret, "Failed to add Certificate to CertificateList.");
85 previous = outCertList;
89 this.SetHandle(first);
94 /// Gets a value that indicates whether the handle is invalid.
96 public override bool IsInvalid
98 get { return (handle == IntPtr.Zero); }
102 /// When overridden in a derived class, executes the code required to free the handle.
104 /// <returns>true if the handle is released successfully</returns>
105 protected override bool ReleaseHandle()
107 if (handle == IntPtr.Zero) // do not release
110 Interop.CkmcTypes.CertListAllFree(handle);
111 this.SetHandle(IntPtr.Zero);