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.Runtime.InteropServices;
21 namespace Tizen.Security.SecureRepository
24 /// Class that represents a certificate.
26 public class Certificate : SafeHandle
29 /// Load Certificate from the given file path.
31 /// <param name="filePath">The path of certificate file to be loaded.</param>
32 /// <returns>Loaded certificate class instance.</returns>
33 /// <exception cref="InvalidOperationException">Invalid certificate file format. Provided file path does not exist or cannot be accessed.</exception>
34 static public Certificate Load(string filePath)
36 IntPtr ptr = new IntPtr();
38 int ret = Interop.CkmcTypes.LoadCertFromFile(filePath, out ptr);
39 Interop.CheckNThrowException(ret, "Failed to load Certificate. file=" + filePath);
41 return new Certificate(ptr);
45 /// A constructor of Certificate that takes the binary and its format.
47 /// <param name="binary">The binary data of a certificate.</param>
48 /// <param name="format">The format of the binary data.</param>
49 public Certificate(byte[] binary, DataFormat format) : base(IntPtr.Zero, true)
51 this.SetHandle(IntPtr.Zero);
56 internal Certificate(IntPtr ptrCkmcCert, bool ownsHandle = true) : base(IntPtr.Zero, ownsHandle)
58 base.SetHandle(ptrCkmcCert);
60 CkmcCert ckmcCert = Marshal.PtrToStructure<CkmcCert>(ptrCkmcCert);
61 Binary = new byte[ckmcCert.size];
62 Marshal.Copy(ckmcCert.rawCert, Binary, 0, Binary.Length);
63 Format = (DataFormat)ckmcCert.dataFormat;
67 /// The binary value of a certificate.
75 /// The format of the binary value.
77 public DataFormat Format
82 internal CkmcCert ToCkmcCert()
84 return new Interop.CkmcCert(new PinnedObject(Binary), Binary.Length, (int)Format);
88 /// Gets a value that indicates whether the handle is invalid.
90 public override bool IsInvalid
92 get { return handle == IntPtr.Zero; }
96 /// When overridden in a derived class, executes the code required to free the handle.
98 /// <returns>true if the handle is released successfully.</returns>
99 protected override bool ReleaseHandle()
101 if (IsInvalid) // do not release
103 Interop.CkmcTypes.CertFree(handle);
104 this.SetHandle(IntPtr.Zero);