--- /dev/null
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
--- /dev/null
+<manifest>
+ <request>
+ <domain name="_"/>
+ </request>
+</manifest>
--- /dev/null
+%{!?dotnet_assembly_path: %define dotnet_assembly_path %{_datadir}/assembly}
+
+%if 0%{?tizen_build_devel_mode}
+%define BUILDCONF Debug
+%else
+%define BUILDCONF Release
+%endif
+
+Name: csapi-security
+Summary: Tizen Security API for C#
+Version: 1.0.0
+Release: 1
+Group: Development/Libraries
+License: Apache-2.0
+URL: https://www.tizen.org
+Source0: %{name}-%{version}.tar.gz
+Source1: %{name}.manifest
+
+# Mono
+BuildRequires: mono-compiler
+BuildRequires: mono-devel
+
+# C# API default dependencies
+BuildRequires: csapi-tizen
+BuildRequires: pkgconfig(glib-2.0)
+
+# privilege-info
+BuildRequires: pkgconfig(privilege-info)
+
+# key-manager
+BuildRequires: pkgconfig(key-manager)
+
+%description
+Tizen Security API for C#
+
+%prep
+%setup -q
+
+cp %{SOURCE1} .
+
+%define Assemblies Tizen.Security
+
+%build
+for ASM in %{Assemblies}; do
+xbuild $ASM/$ASM.csproj \
+ /p:Configuration=%{BUILDCONF} \
+ /p:ReferencePath=%{dotnet_assembly_path}
+done
+
+%install
+# Assemblies
+mkdir -p %{buildroot}%{dotnet_assembly_path}
+for ASM in %{Assemblies}; do
+install -p -m 644 $ASM/bin/%{BUILDCONF}/$ASM.dll %{buildroot}%{dotnet_assembly_path}
+done
+
+# License
+mkdir -p %{buildroot}%{_datadir}/license
+cp LICENSE %{buildroot}%{_datadir}/license/%{name}
+
+%files
+%manifest %{name}.manifest
+%attr(644,root,root) %{dotnet_assembly_path}/*.dll
+%attr(644,root,root) %{_datadir}/license/%{name}
--- /dev/null
+/obj
+/bin
--- /dev/null
+<Dictionary>
+ <Words>
+ <Recognized>
+ <Word>Tizen</Word>
+ <Word>Security</Word>
+ <Word>SecureRepository</Word>
+ <Word>Privilege</Word>
+ </Recognized>
+ </Words>
+</Dictionary>
--- /dev/null
+using System;
+
+internal static partial class Interop
+{
+ private const int TizenErrorKeyManager = -0x01E10000;
+
+ internal enum KeyManagerError : int
+ {
+ // TODO : Add reference to real Tizen project
+ //None = Tizen.Internals.Errors.ErrorCode.None,
+ //InvalidParameter = Tizen.Internals.Errors.ErrorCode.InvalidParameter
+ None = 0, // CKMC_ERROR_NONE
+ InvalidParameter = -22, // CKMC_ERROR_INVALID_PARAMETER
+ VerificationFailed = TizenErrorKeyManager | 0x0D // CKMC_ERROR_VERIFICATION_FAILED
+ };
+
+ internal class KeyManagerExceptionFactory
+ {
+ internal const string LogTag = "Tizen.Security.SecureRepository";
+
+ internal static void CheckNThrowException(int err, string msg)
+ {
+ if (err == (int)KeyManagerError.None)
+ return;
+
+ switch (err)
+ {
+ case (int)KeyManagerError.InvalidParameter:
+ throw new ArgumentException(msg + ", error=" + Interop.GetErrorMessage(err));
+ default:
+ throw new InvalidOperationException(msg + ", error=" + Interop.GetErrorMessage(err));
+ }
+ }
+ }
+}
--- /dev/null
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class CkmcManager
+ {
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_save_key", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcSaveKey(string alias, CkmcKey key, CkmcPolicy policy);
+ // int ckmc_save_key(const char *alias, const ckmc_key_s key, const ckmc_policy_s policy);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_key", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetKey(string alias, string password, out IntPtr key);
+ // int ckmc_get_key(const char *alias, const char *password, ckmc_key_s **ppkey);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_key_alias_list", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetKeyAliasList(out IntPtr aliases);
+ // int ckmc_get_key_alias_list(ckmc_alias_list_s **ppalias_list);
+
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_save_cert", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcSaveCert(string alias, CkmcCert cert, CkmcPolicy policy);
+ // int ckmc_save_cert(const char *alias, const ckmc_cert_s cert, const ckmc_policy_s policy);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_cert", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetCert(string alias, string password, out IntPtr data);
+ // int ckmc_get_cert(const char *alias, const char *password, ckmc_cert_s** ppcert);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_cert_alias_list", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetCertAliasList(out IntPtr aliases);
+ // int ckmc_get_cert_alias_list(ckmc_alias_list_s **ppalias_list);
+
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_save_data", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcSaveData(string alias, CkmcRawBuffer data, CkmcPolicy policy);
+ // int ckmc_save_data(const char *alias, ckmc_raw_buffer_s data, const ckmc_policy_s policy);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_data", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetData(string alias, string password, out IntPtr data);
+ // int ckmc_get_data(const char* alias, const char* password, ckmc_raw_buffer_s **ppdata);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_data_alias_list", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetDataAliasList(out IntPtr aliases);
+ // int ckmc_get_data_alias_list(ckmc_alias_list_s **ppalias_list);
+
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_remove_alias", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcRemoveAlias(string alias);
+ // int ckmc_remove_alias(const char *alias);
+
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_save_pkcs12", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcSavePkcs12(string alias, IntPtr p12, CkmcPolicy keyPolicy, CkmcPolicy certPolicy);
+ // int ckmc_save_pkcs12(const char *alias, const ckmc_pkcs12_s* pkcs, const ckmc_policy_s key_policy, const ckmc_policy_s cert_policy);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_pkcs12", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetPkcs12(string alias, string keyPassword, string certPassword, out IntPtr pkcs12);
+ // int ckmc_get_pkcs12(const char *alias, const char *key_password, const char* cert_password, ckmc_pkcs12_s **pkcs12);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_set_permission", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcSetPermission(string alias, string accessor, int permissions);
+ // int ckmc_set_permission(const char *alias, const char *accessor, int permissions);
+
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_create_key_pair_rsa", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcCreateKeyPairRsa(int size, string privateKeyAlias, string publicKeyAlias,
+ CkmcPolicy privateKeyPolicy, CkmcPolicy publicKeyPolicy);
+ // int ckmc_create_key_pair_rsa(const size_t size, const char* private_key_alias, const char* public_key_alias,
+ // const ckmc_policy_s policy_private_key, const ckmc_policy_s policy_public_key);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_create_key_pair_dsa", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcCreateKeyPairDsa(int size, string privateKeyAlias, string publicKeyAlias,
+ CkmcPolicy privateKeyPolicy, CkmcPolicy publicKeyPolicy);
+ // int ckmc_create_key_pair_dsa(const size_t size, const char* private_key_alias, const char* public_key_alias,
+ // const ckmc_policy_s policy_private_key, const ckmc_policy_s policy_public_key);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_create_key_pair_ecdsa", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcCreateKeyPairEcdsa(int ecType, string privateKeyAlias, string publicKeyAlias,
+ CkmcPolicy privateKeyPolicy, CkmcPolicy publicKeyPolicy);
+ // int ckmc_create_key_pair_ecdsa(const size_t size, const char* private_key_alias, const char* public_key_alias,
+ // const ckmc_policy_s policy_private_key, const ckmc_policy_s policy_public_key);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_create_key_aes", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcCreateKeyAes(int size, string ceyAlias, CkmcPolicy keyPolicy);
+ // int ckmc_create_key_aes(size_t size, const char* key_alias, ckmc_policy_s key_policy);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_create_signature", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcCreateSignature(string privateKeyAlias, string password, CkmcRawBuffer message,
+ int hashAlgorithm, int paddingAlgorithm, out IntPtr signature);
+ // int ckmc_create_signature(const char *private_key_alias, const char* password, const ckmc_raw_buffer_s message,
+ // const ckmc_hash_algo_e hash, const ckmc_rsa_padding_algo_e padding, ckmc_raw_buffer_s **ppsignature);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_verify_signature", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcVerifySignature(string publicKeyAlias, string password, CkmcRawBuffer message,
+ CkmcRawBuffer signature, int hashAlgorithm, int paddingAlgorithm);
+ // int ckmc_verify_signature(const char *public_key_alias, const char* password, const ckmc_raw_buffer_s message,
+ // const ckmc_raw_buffer_s signature, const ckmc_hash_algo_e hash, const ckmc_rsa_padding_algo_e padding);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_encrypt_data", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcEncryptData(IntPtr parameters, string keyAlias, string password, CkmcRawBuffer plainText, out IntPtr cipherText);
+ // int ckmc_encrypt_data(ckmc_param_list_h params, const char* key_alias, const char* password,
+ // const ckmc_raw_buffer_s decrypted, ckmc_raw_buffer_s **ppencrypted);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_decrypt_data", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcDecryptData(IntPtr parameters, string keyAlias, string password, CkmcRawBuffer cipherText, out IntPtr plainText);
+ // int ckmc_decrypt_data(ckmc_param_list_h params, const char* key_alias, const char* password,
+ // const ckmc_raw_buffer_s encrypted, ckmc_raw_buffer_s **ppdecrypted);
+
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_cert_chain", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetCertChain(IntPtr cert, IntPtr untrustedCerts, out IntPtr certChain);
+ // int ckmc_get_cert_chain(const ckmc_cert_s *cert, const ckmc_cert_list_s* untrustedcerts, ckmc_cert_list_s **ppcert_chain_list);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_get_cert_chain_with_trustedcert", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGetCertChainWithTrustedCerts(IntPtr cert, IntPtr untrustedCerts, IntPtr trustedCerts,
+ bool useTrustedSystemCerts, out IntPtr certChain);
+ // int ckmc_get_cert_chain_with_trustedcert(const ckmc_cert_s *cert, const ckmc_cert_list_s* untrustedcerts,
+ // const ckmc_cert_list_s* trustedcerts, const bool use_trustedsystemcerts, ckmc_cert_list_s **ppcert_chain_list);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_ocsp_check", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcOcspCheck(IntPtr certChain, ref int ocspStatus);
+ // int ckmc_ocsp_check(const ckmc_cert_list_s *pcert_chain_list, ckmc_ocsp_status_e* ocsp_status);
+ }
+}
--- /dev/null
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct CkmcPolicy
+ {
+ public CkmcPolicy(string password, bool extractable)
+ {
+ this.password = password;
+ this.extractable = extractable;
+ }
+ [MarshalAs(UnmanagedType.LPTStr)]
+ public readonly string password;
+ [MarshalAs(UnmanagedType.Bool)]
+ public readonly bool extractable;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct CkmcKey
+ {
+ public CkmcKey(IntPtr binary, int keySize, int keyType, IntPtr password)
+ {
+ this.rawKey = binary;
+ this.size = (uint)keySize;
+ this.keyType = keyType;
+ this.password = password;
+ }
+ public readonly IntPtr rawKey;
+ public readonly uint size;
+ public readonly int keyType;
+ public readonly IntPtr password;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct CkmcCert
+ {
+ public CkmcCert(IntPtr binary, int size, int dataFormat)
+ {
+ this.rawCert = binary;
+ this.size = (uint)size;
+ this.dataFormat = dataFormat;
+ }
+ public readonly IntPtr rawCert;
+ public readonly uint size;
+ public readonly int dataFormat;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct CkmcRawBuffer
+ {
+ public CkmcRawBuffer(IntPtr binary, int size)
+ {
+ this.data = binary;
+ this.size = (uint)size;
+ }
+ public readonly IntPtr data;
+ public readonly uint size;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct CkmcAliasList
+ {
+ public readonly IntPtr alias;
+ public readonly IntPtr next;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct CkmcCertList
+ {
+ public CkmcCertList(IntPtr cert, IntPtr next)
+ {
+ this.cert = cert;
+ this.next = next;
+ }
+ public readonly IntPtr cert;
+ public readonly IntPtr next;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct CkmcPkcs12
+ {
+ public CkmcPkcs12(IntPtr privateKey, IntPtr certificate, IntPtr caChain)
+ {
+ this.privateKey = privateKey;
+ this.certificate = certificate;
+ this.caChain = caChain;
+ }
+ public readonly IntPtr privateKey;
+ public readonly IntPtr certificate;
+ public readonly IntPtr caChain;
+ }
+
+
+ static public string GetErrorMessage(int errorCode)
+ {
+ IntPtr errorPtr = CkmcTypes.GetErrorMessage(errorCode);
+ return Marshal.PtrToStringAuto(errorPtr);
+ }
+
+
+ internal static partial class CkmcTypes
+ {
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_key_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcKeyFree(IntPtr buffer);
+ // void ckmc_key_free(ckmc_key_s *key);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_buffer_new", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcBufferNew(byte[] data, uint size, out IntPtr buffer);
+ // int ckmc_buffer_new(unsigned char *data, size_t size, ckmc_raw_buffer_s** ppbuffer);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_buffer_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcBufferFree(IntPtr buffer);
+ // void ckmc_buffer_free(ckmc_raw_buffer_s* buffer);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_cert_new", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcCertNew(byte[] rawCert, uint size, int dataFormat, out IntPtr cert);
+ // int ckmc_cert_new(unsigned char *raw_cert, size_t cert_size, ckmc_data_format_e data_format, ckmc_cert_s** ppcert);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_cert_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcCertFree(IntPtr buffer);
+ // void ckmc_cert_free(ckmc_cert_s *cert);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_load_cert_from_file", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcLoadCertFromFile(string filePath, out IntPtr cert);
+ // int ckmc_load_cert_from_file(const char *file_path, ckmc_cert_s **cert);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_pkcs12_new", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcPkcs12New(string filePath, out IntPtr cert);
+ // int ckmc_pkcs12_new(ckmc_key_s *private_key, ckmc_cert_s* cert, ckmc_cert_list_s *ca_cert_list, ckmc_pkcs12_s** pkcs12_bundle);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_load_from_pkcs12_file", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcLoadFromPkcs12File(string filePath, string password, out IntPtr privateKey, out IntPtr cert, out IntPtr caCertList);
+ // int ckmc_load_from_pkcs12_file(const char *file_path, const char* passphrase, ckmc_key_s **private_key, ckmc_cert_s** cert, ckmc_cert_list_s **ca_cert_list);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_pkcs12_load", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcPkcs12Load(string filePath, string password, out IntPtr pkcs12);
+ // int ckmc_pkcs12_load(const char *file_path, const char* passphrase, ckmc_pkcs12_s **pkcs12_bundle);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_pkcs12_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcPkcs12Free(IntPtr pkcs12);
+ // void ckmc_pkcs12_free(ckmc_pkcs12_s *pkcs12);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_alias_list_new", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcAliasListNew(string alias, out IntPtr aliasList);
+ // int ckmc_alias_list_new(char *alias, ckmc_alias_list_s **ppalias_list);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_alias_list_add", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcAliasListAdd(IntPtr previous, string alias, out IntPtr aliasList);
+ // int ckmc_alias_list_add(ckmc_alias_list_s *previous, char* alias, ckmc_alias_list_s **pplast);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_alias_list_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcAliasListFree(IntPtr first);
+ // void ckmc_alias_list_free(ckmc_alias_list_s* first);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_alias_list_all_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcAliasListAllFree(IntPtr first);
+ // void ckmc_alias_list_all_free(ckmc_alias_list_s* first);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_cert_list_new", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcCertListNew(IntPtr cert, out IntPtr certList);
+ // int ckmc_cert_list_new(ckmc_cert_s *cert, ckmc_cert_list_s **ppcert_list);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_cert_list_add", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcCertListAdd(IntPtr previous, IntPtr cert, out IntPtr certList);
+ // int ckmc_cert_list_add(ckmc_cert_list_s *previous, ckmc_cert_s *cert, ckmc_cert_list_s** pplast);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_cert_list_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcCertListFree(IntPtr first);
+ // void ckmc_cert_list_free(ckmc_cert_list_s *first);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_cert_list_all_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcCertListAllFree(IntPtr first);
+ // void ckmc_cert_list_all_free(ckmc_cert_list_s *first);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_param_list_new", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcParamListNew(out IntPtr paramList);
+ // int ckmc_param_list_new(ckmc_param_list_h *pparams);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_param_list_set_integer", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcParamListSetInteger(IntPtr paramList, int name, long value);
+ // int ckmc_param_list_set_integer(ckmc_param_list_h params, ckmc_param_name_e name, uint64_t value);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_param_list_set_buffer", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcParamListSetBuffer(IntPtr paramList, int name, IntPtr buffer);
+ // int ckmc_param_list_set_buffer(ckmc_param_list_h params, ckmc_param_name_e name, const ckmc_raw_buffer_s* buffer);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_param_list_get_integer", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcParamListGetInteger(IntPtr paramList, int name, out long value);
+ // int ckmc_param_list_get_integer(ckmc_param_list_h params, ckmc_param_name_e name, uint64_t *pvalue);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_param_list_get_buffer", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcParamListGetBuffer(IntPtr paramList, int name, out IntPtr buffer);
+ // int ckmc_param_list_get_buffer(ckmc_param_list_h params, ckmc_param_name_e name, ckmc_raw_buffer_s **ppbuffer);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_param_list_free", CallingConvention = CallingConvention.Cdecl)]
+ public static extern void CkmcParamListFree(IntPtr first);
+ // void ckmc_param_list_free(ckmc_param_list_h params);
+
+ [DllImport(Libraries.KeyManagerClient, EntryPoint = "ckmc_generate_new_params", CallingConvention = CallingConvention.Cdecl)]
+ public static extern int CkmcGenerateNewParam(int algoType, out IntPtr paramList);
+ // int ckmc_generate_new_params(ckmc_algo_type_e type, ckmc_param_list_h *pparams);
+
+ [DllImport(Libraries.TizenBaseCommon, EntryPoint = "get_error_message", CallingConvention = CallingConvention.Cdecl)]
+ public static extern IntPtr GetErrorMessage(int err);
+ // char *get_error_message(int err);
+
+ }
+}
+
--- /dev/null
+// Copyright 2016 by Samsung Electronics, Inc.,
+//
+// This software is the confidential and proprietary information
+// of Samsung Electronics, Inc. ("Confidential Information"). You
+// shall not disclose such Confidential Information and shall use
+// it only in accordance with the terms of the license agreement
+// you entered into with Samsung.
+
+internal static partial class Interop
+{
+ internal static partial class Libraries
+ {
+ public const string PrivilegeInformation = "libprivilege-info.so.1.0.0";
+ public const string KeyManagerClient = "libkey-manager-client.so.1";
+ public const string TizenBaseCommon = "libcapi-base-common.so.0";
+ }
+}
--- /dev/null
+// Copyright 2016 by Samsung Electronics, Inc.,
+//
+// This software is the confidential and proprietary information
+// of Samsung Electronics, Inc. ("Confidential Information"). You
+// shall not disclose such Confidential Information and shall use
+// it only in accordance with the terms of the license agreement
+// you entered into with Samsung.
+
+using System;
+using System.Runtime.InteropServices;
+
+using Tizen.Security;
+
+internal static partial class Interop
+{
+ internal static partial class PrivilegeInformation
+ {
+ [DllImport(Libraries.PrivilegeInformation, EntryPoint = "privilege_info_get_display_name")]
+ internal static extern int GetDisplayName(string apiVersion, string privilege, out string displayName);
+
+ [DllImport(Libraries.PrivilegeInformation, EntryPoint = "privilege_info_get_description")]
+ internal static extern int GetDescription(string apiVersion, string privilege, out string description);
+
+ [DllImport(Libraries.PrivilegeInformation, EntryPoint = "privilege_info_get_display_name_by_pkgtype")]
+ internal static extern int GetDisplayNameByPkgtype(string packageType, string apiVersion, string privilege, out string displayName);
+
+ [DllImport(Libraries.PrivilegeInformation, EntryPoint = "privilege_info_get_description_by_pkgtype")]
+ internal static extern int GetDescriptionByPkgtype(string packageType, string apiVersion, string privilege, out string description);
+ }
+}
--- /dev/null
+using System;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+[assembly: AssemblyTitle("Tizen.Security")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Samsung Electronics")]
+[assembly: AssemblyProduct("Tizen.Security")]
+[assembly: AssemblyCopyright("Copyright (c) 2016 Samsung Electronics Co., Ltd")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+[assembly: ComVisible(false)]
+[assembly: CLSCompliant(true)]
+
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
--- /dev/null
+using System;
+using System.Runtime.InteropServices;
+using static Interop;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// Class that represents a certificate.
+ /// </summary>
+ public class Certificate : SafeHandle
+ {
+ /// <summary>
+ /// A constructor of Certificate that takes the binary and its format.
+ /// </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)
+ {
+ this.SetHandle(IntPtr.Zero);
+ Binary = binary;
+ Format = format;
+ }
+
+ internal Certificate(IntPtr ptrCkmcCert, bool ownsHandle = true) : base(IntPtr.Zero, ownsHandle)
+ {
+ base.SetHandle(ptrCkmcCert);
+
+ CkmcCert ckmcCert = (CkmcCert)Marshal.PtrToStructure(ptrCkmcCert, typeof(CkmcCert));
+ Binary = new byte[ckmcCert.size];
+ Marshal.Copy(ckmcCert.rawCert, Binary, 0, Binary.Length);
+ Format = (DataFormat)ckmcCert.dataFormat;
+ }
+
+ /// <summary>
+ /// The binary value of a certificate.
+ /// </summary>
+ public byte[] Binary
+ {
+ get; set;
+ }
+
+ /// <summary>
+ /// The format of the binary value.
+ /// </summary>
+ public DataFormat Format
+ {
+ get; set;
+ }
+
+ internal CkmcCert ToCkmcCert()
+ {
+ return new Interop.CkmcCert(new PinnedObject(Binary), Binary.Length, (int)Format);
+ }
+
+ /// <summary>
+ /// Gets a value that indicates whether the handle is invalid.
+ /// </summary>
+ public override bool IsInvalid
+ {
+ get { return 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()
+ {
+ if (IsInvalid) // do not release
+ return true;
+ Interop.CkmcTypes.CkmcCertFree(handle);
+ this.SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+}
--- /dev/null
+using System;
+using System.Collections.Generic;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// This class provides the methods handling certificates.
+ /// </summary>
+ public class CertificateManager : Manager
+ {
+ /// <summary>
+ /// Gets a certificate from secure repository.
+ /// </summary>
+ /// <param name="alias">The name of a certificate to retrieve.</param>
+ /// <param name="password">The password used in decrypting a certificate value.
+ /// If password of policy is provided in SaveCertificate(), the same password should be provided
+ /// </param>
+ /// <returns>A certificate specified by alias.</returns>
+ static public Certificate GetCertificate(string alias, string password)
+ {
+ IntPtr ptr = new IntPtr();
+
+ int ret = Interop.CkmcManager.CkmcGetCert(alias, password, out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get certificate. alias=" + alias);
+
+ return new Certificate(ptr);
+ }
+
+ /// <summary>
+ /// Gets all alias of certificates which the client can access.
+ /// </summary>
+ /// <returns>all alias of certificates which the client can access.</returns>
+ static public IEnumerable<string> GetCertificateAliases()
+ {
+ IntPtr ptr = new IntPtr();
+ int ret = Interop.CkmcManager.CkmcGetCertAliasList(out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get certificate aliases.");
+
+ return new SafeAliasListHandle(ptr).Aliases;
+ }
+
+ /// <summary>
+ /// Stores a certificate inside secure repository based on the provided policy.
+ /// </summary>
+ /// <param name="alias">The name of a certificate to be stored.</param>
+ /// <param name="cert">The certificate's binary value to be stored.</param>
+ /// <param name="policy">The policy about how to store a certificate securely.</param>
+ static public void SaveCertificate(string alias, Certificate cert, Policy policy)
+ {
+ int ret = Interop.CkmcManager.CkmcSaveCert(alias, cert.ToCkmcCert(), policy.ToCkmcPolicy());
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to save certificate. alias=" + alias);
+ }
+
+ /// <summary>
+ /// Verifies a certificate chain and returns that chain.
+ /// </summary>
+ /// <param name="certificate">The certificate to be verified.</param>
+ /// <param name="untrustedCertificates">The untrusted CA certificates to be used in verifying a certificate chain.</param>
+ /// <returns>A newly created certificate chain.</returns>
+ /// <remarks>The trusted root certificate of the chain should exist in the system's certificate storage.</remarks>
+ static public IEnumerable<Certificate> GetCertificateChain(Certificate certificate,
+ IEnumerable<Certificate> untrustedCertificates)
+ {
+ IntPtr ptrCertChain = new IntPtr();
+
+ SafeCertificateListHandle untrustedCerts = new SafeCertificateListHandle(untrustedCertificates);
+
+ int ret = Interop.CkmcManager.CkmcGetCertChain(new PinnedObject(certificate.ToCkmcCert()),
+ untrustedCerts.ToCkmcCertificateListPtr(), out ptrCertChain);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get certificate chain");
+
+ SafeCertificateListHandle certChain = new SafeCertificateListHandle(ptrCertChain);
+ return certChain.Certificates;
+ }
+
+ /// <summary>
+ /// Verifies a certificate chain and returns that chain using user entered trusted and untrusted CA certificates.
+ /// </summary>
+ /// <param name="certificate">The certificate to be verified.</param>
+ /// <param name="untrustedCertificates">The untrusted CA certificates to be used in verifying a certificate chain.</param>
+ /// <param name="trustedCertificates">The trusted CA certificates to be used in verifying a certificate chain.</param>
+ /// <param name="useTrustedSystemCertificates">The flag indicating the use of the trusted root certificates in the system's certificate storage.</param>
+ /// <returns>A newly created certificate chain.</returns>
+ static public IEnumerable<Certificate> GetCertificateChain(Certificate certificate,
+ IEnumerable<Certificate> untrustedCertificates,
+ IEnumerable<Certificate> trustedCertificates,
+ bool useTrustedSystemCertificates)
+ {
+ IntPtr ptrCertChain = new IntPtr();
+ SafeCertificateListHandle untrustedCerts = new SafeCertificateListHandle(untrustedCertificates);
+ SafeCertificateListHandle trustedCerts = new SafeCertificateListHandle(trustedCertificates);
+
+ int ret = Interop.CkmcManager.CkmcGetCertChainWithTrustedCerts(new PinnedObject(certificate.ToCkmcCert()),
+ untrustedCerts.ToCkmcCertificateListPtr(), trustedCerts.ToCkmcCertificateListPtr(), useTrustedSystemCertificates,
+ out ptrCertChain);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get certificate chain with trusted certificates");
+
+ SafeCertificateListHandle certChain = new SafeCertificateListHandle(ptrCertChain);
+
+ return certChain.Certificates;
+ }
+
+ /// <summary>
+ /// Perform OCSP which checks certificate is whether revoked or not.
+ /// </summary>
+ /// <param name="certificateChain">Valid certificate chain to perform OCSP check.</param>
+ /// <returns>A status result of OCSP check.</returns>
+ static public OcspStatus CheckOcsp(IEnumerable<Certificate> certificateChain)
+ {
+ int ocspStatus = (int)OcspStatus.Good;
+ SafeCertificateListHandle certChain = new SafeCertificateListHandle(certificateChain);
+ int ret = Interop.CkmcManager.CkmcOcspCheck(certChain.ToCkmcCertificateListPtr(), ref ocspStatus);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get certificate chain with trusted certificates");
+ return (OcspStatus)ocspStatus;
+ }
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A class holding parameters for AES algorithm with CBC mode.
+ /// </summary>
+ public class AesCbcCipherParameters : AesCipherParameters
+ {
+ /// <summary>
+ /// A default constructor
+ /// </summary>
+ /// <remarks>The CipherAlgorithmType in CipherParameters is set to CipherAlgorithmType.AesCbc.</remarks>
+ public AesCbcCipherParameters() : base(CipherAlgorithmType.AesCbc)
+ {
+ }
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A class holding parameters for AES algorithm with CFB mode.
+ /// </summary>
+ public class AesCfbCipherParameters : AesCipherParameters
+ {
+ /// <summary>
+ /// A default constructor
+ /// </summary>
+ /// <remarks>The CipherAlgorithmType in CipherParameters is set to CipherAlgorithmType.AesCfb.</remarks>
+ public AesCfbCipherParameters() : base(CipherAlgorithmType.AecCfb)
+ {
+ }
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A abstract class holding parameters for AES algorithm.
+ /// </summary>
+ public abstract class AesCipherParameters : CipherParameters
+ {
+ /// <summary>
+ /// A constructor with algorithm
+ /// </summary>
+ /// <param name="algorithm">An algorithm that this parameters are prepared for.</param>
+ public AesCipherParameters(CipherAlgorithmType algorithm) : base(algorithm)
+ {
+ }
+
+ /// <summary>
+ /// An initialization vector.
+ /// </summary>
+ public byte[] IV
+ {
+ get { return GetBuffer(CipherParameterName.IV); }
+ set { Add(CipherParameterName.IV, value); }
+ }
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A class holding parameters for AES algorithm with counter mode.
+ /// </summary>
+ public class AesCtrCipherParameters : AesCipherParameters
+ {
+ /// <summary>
+ /// A default constructor
+ /// </summary>
+ /// <remarks>The CipherAlgorithmType in CipherParameters is set to CipherAlgorithmType.AesCtr.</remarks>
+ public AesCtrCipherParameters() : base(CipherAlgorithmType.AesCtr)
+ {
+ }
+
+ /// <summary>
+ /// Length of counter block in bits.
+ /// </summary>
+ /// <remarks>Optional, only 128b is supported at the moment.</remarks>
+ public long CounterLength
+ {
+ get
+ {
+ return (uint)GetInteger(CipherParameterName.CounterLength);
+ }
+ set
+ {
+ Add(CipherParameterName.CounterLength, value);
+ }
+ }
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A class holding parameters for AES algorithm with GCM mode.
+ /// </summary>
+ public class AesGcmCipherParameters : AesCipherParameters
+ {
+ /// <summary>
+ /// A default constructor
+ /// </summary>
+ /// <remarks>The CipherAlgorithmType in CipherParameters is set to CipherAlgorithmType.AesGcm.</remarks>
+ public AesGcmCipherParameters() : base(CipherAlgorithmType.AesGcm)
+ {
+ }
+
+ /// <summary>
+ /// GCM tag length in bits.
+ /// </summary>
+ /// <remarks>One of {32, 64, 96, 104, 112, 120, 128} (optional, if not present the length 128 is used.</remarks>
+ public long TagLength
+ {
+ get { return GetInteger(CipherParameterName.TagLength); }
+ set { Add(CipherParameterName.TagLength, value); }
+ }
+
+ /// <summary>
+ /// Additional authentication data(optional)
+ /// </summary>
+ public byte[] AAD
+ {
+ get { return GetBuffer(CipherParameterName.AAD); }
+ set { Add(CipherParameterName.AAD, value); }
+ }
+ }
+}
--- /dev/null
+using System;
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// This class provides the methods encrypting and decrypting data.
+ /// </summary>
+ public class Cipher
+ {
+ private readonly CipherParameters _parameters;
+
+ /// <summary>
+ /// A constructor of Cipher that takes the algorithm specific parameters.
+ /// </summary>
+ /// <param name="parameters">The algorithm specific parameters.</param>
+ public Cipher(CipherParameters parameters)
+ {
+ _parameters = parameters;
+ }
+
+ /// <summary>
+ /// The algorithm specific parameters.
+ /// </summary>
+ public CipherParameters Parameters
+ {
+ get { return _parameters; }
+ }
+
+ /// <summary>
+ /// Decrypts data using selected key and algorithm.
+ /// </summary>
+ /// <param name="keyAlias">Alias of the key to be used for decryption.</param>
+ /// <param name="password">The password used in decrypting a key value.
+ /// If password of policy is provided in SaveKey(), the same password should be provided</param>
+ /// <param name="cipherText">Data to be decrypted (some algorithms may require additional
+ /// information embedded in encrypted data.AES GCM is an example).</param>
+ /// <returns>Decrypted data.</returns>
+ /// <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);
+
+ int ret = Interop.CkmcManager.CkmcDecryptData(Parameters.PtrCkmcParamList, keyAlias, password, cipherTextBuff, out ptrPlainText);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to decrypt data");
+
+ return new SafeRawBufferHandle(ptrPlainText).Data;
+ }
+
+ /// <summary>
+ /// Encrypts data using selected key and algorithm.
+ /// </summary>
+ /// <param name="keyAlias">Alias of the key to be used for encryption.</param>
+ /// <param name="password">The password used in decrypting a key value.
+ /// If password of policy is provided in SaveKey(), the same password should be provided</param>
+ /// <param name="plainText">Data to be encrypted. In case of AES algorithm there are no restrictions on the size of data.
+ /// For RSA the size must be smaller or equal to (key_size_in bytes - 42).
+ /// Example: for 1024 RSA key the maximum data size is 1024/8 - 42 = 86.</param>
+ /// <returns>Encrypted data.</returns>
+ /// <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.CkmcEncryptData(Parameters.PtrCkmcParamList, keyAlias, password, plainTextBuff, out ptrCipherText);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to encrypt data");
+
+ return new SafeRawBufferHandle(ptrCipherText).Data;
+ }
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// Enumeration for crypto cipher algorithm types.
+ /// </summary>
+ public enum CipherAlgorithmType : int
+ {
+ /// <summary>
+ /// AES-CTR algorithm
+ /// Supported parameters:
+ /// - ParameterName.AlgorithmType = AesCtr(mandatory),
+ /// - ParameterName.IV = 16 - byte initialization vector(mandatory)
+ /// - ParameterName.CounterLength = length of counter block in bits
+ /// (optional, only 128b is supported at the moment)
+ /// </summary>
+ AesCtr = 0x01,
+ /// <summary>
+ /// AES-CBC algorithm
+ /// Supported parameters:
+ /// - ParameterName.AlgorithmType = AesCbc(mandatory),
+ /// - ParameterName.IV = 16-byte initialization vector(mandatory)
+ /// </summary>
+ AesCbc,
+ /// <summary>
+ /// AES-GCM algorithm
+ /// Supported parameters:
+ /// - ParameterName.AlgorithmType = AesGcm(mandatory),
+ /// - ParameterName.IV = initialization vector(mandatory)
+ /// - ParameterName.TagLength = GCM tag length in bits. One of
+ /// {32, 64, 96, 104, 112, 120, 128} (optional, if not present the length 128 is used)
+ /// - CKMC_PARAM_ED_AAD = additional authentication data(optional)
+ /// </summary>
+ AesGcm,
+ /// <summary>
+ /// AES-CFB algorithm
+ /// Supported parameters:
+ /// - ParameterName.AlgorithmType = AecCfb(mandatory),
+ /// - ParameterName.IV = 16-byte initialization vector(mandatory)
+ /// </summary>
+ AecCfb,
+ /// <summary>
+ /// RSA-OAEP algorithm
+ /// Supported parameters:
+ /// - ParameterName.AlgorithmType = RsaOaep(required),
+ /// - ParameterName.Label = label to be associated with the message
+ /// (optional, not supported at the moment)
+ /// </summary>
+ RsaOaep
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// Enumeration for cipher algorithm parameters.
+ /// </summary>
+ public enum CipherParameterName : int
+ {
+ /// <summary>
+ /// Algorithm Type
+ /// </summary>
+ AlgorithmType = 0x01,
+ /// <summary>
+ /// Initial Vector, 16B buffer (up to 2^64-1 bytes long in case of AES GCM)
+ /// </summary>
+ IV = 101,
+ /// <summary>
+ /// Integer - ctr length in bits
+ /// </summary>
+ CounterLength = 102,
+ /// <summary>
+ /// Additional authenticated data(AAD)
+ /// </summary>
+ AAD = 103,
+ /// <summary>
+ /// Tag Length
+ /// </summary>
+ TagLength = 104,
+ /// <summary>
+ /// Label
+ /// </summary>
+ Label = 105
+ }
+
+}
--- /dev/null
+using System;
+using System.Runtime.InteropServices;
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A abstract class holding parameters for encryption and decryption.
+ /// </summary>
+ abstract public class CipherParameters : SafeHandle
+ {
+ /// <summary>
+ /// A constructor with algorithm
+ /// </summary>
+ /// <param name="algorithm">An algorithm that this parameters are prepared for.</param>
+ public CipherParameters(CipherAlgorithmType algorithm) : base(IntPtr.Zero, true)
+ {
+ IntPtr ptrParams;
+ Interop.CkmcTypes.CkmcGenerateNewParam((int)algorithm, out ptrParams);
+ this.SetHandle(ptrParams);
+ }
+
+ /// <summary>
+ /// Adds integer parameter.
+ /// </summary>
+ /// <param name="name">Parameter name.</param>
+ /// <param name="value">Parameter value.</param>
+ protected void Add(CipherParameterName name, long value)
+ {
+ int ret = Interop.CkmcTypes.CkmcParamListSetInteger(PtrCkmcParamList, (int)name, value);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to add parameter.");
+ }
+
+ /// <summary>
+ /// Adds byte array parameter.
+ /// </summary>
+ /// <param name="name">Parameter name.</param>
+ /// <param name="value">Parameter value.</param>
+ protected void Add(CipherParameterName name, byte[] value)
+ {
+ Interop.CkmcRawBuffer rawBuff = new Interop.CkmcRawBuffer(new PinnedObject(value), value.Length);
+ int ret = Interop.CkmcTypes.CkmcParamListSetBuffer(PtrCkmcParamList, (int)name, new PinnedObject(rawBuff));
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to add parameter.");
+ }
+
+ /// <summary>
+ /// Gets integer parameter.
+ /// </summary>
+ /// <param name="name">Parameter name.</param>
+ protected long GetInteger(CipherParameterName name)
+ {
+ long value = 0;
+ int ret = Interop.CkmcTypes.CkmcParamListGetInteger(PtrCkmcParamList, (int)name, out value);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get parameter.");
+ return value;
+ }
+
+ /// <summary>
+ /// Gets byte array parameter.
+ /// </summary>
+ /// <param name="name">Parameter name.</param>
+ protected byte[] GetBuffer(CipherParameterName name)
+ {
+ IntPtr ptr = new IntPtr();
+
+ int ret = Interop.CkmcTypes.CkmcParamListGetBuffer(PtrCkmcParamList, (int)name, out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get parameter.");
+
+ return new SafeRawBufferHandle(ptr).Data;
+ }
+
+ /// <summary>
+ /// Cipher algorithm type.
+ /// </summary>
+ public CipherAlgorithmType Algorithm
+ {
+ get { return (CipherAlgorithmType)GetInteger(CipherParameterName.AlgorithmType); }
+ }
+
+ internal IntPtr PtrCkmcParamList
+ {
+ get { return handle; }
+ }
+
+ /// <summary>
+ /// Gets a value that indicates whether the handle is invalid.
+ /// </summary>
+ public override bool IsInvalid
+ {
+ get { return 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()
+ {
+ if (IsInvalid) // do not release
+ return true;
+ Interop.CkmcTypes.CkmcParamListFree(handle);
+ this.SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A class holding parameters for DSA signature algorithm.
+ /// </summary>
+ public class DsaSignatureParameters : SignatureParameters
+ {
+ /// <summary>
+ /// A default constructor
+ /// </summary>
+ /// <remarks>The SignatureAlgorithmType in SignatureParameters is set to SignatureAlgorithmType.DsaSignature.</remarks>
+ public DsaSignatureParameters() : base(SignatureAlgorithmType.DsaSignature)
+ {
+ }
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A class holding parameters for ECDSA signature algorithm.
+ /// </summary>
+ public class EcdsaSignatureParameters : SignatureParameters
+ {
+ /// <summary>
+ /// A default constructor
+ /// </summary>
+ /// <remarks>The SignatureAlgorithmType in SignatureParameters is set to SignatureAlgorithmType.EcdsaSignature.</remarks>
+ public EcdsaSignatureParameters() : base(SignatureAlgorithmType.EcdsaSignature)
+ {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// Enumeration for hash algorithm
+ /// </summary>
+ public enum HashAlgorithm : int
+ {
+ /// <summary>
+ /// No Hash Algorithm
+ /// </summary>
+ None = 0,
+ /// <summary>
+ /// Hash Algorithm SHA1
+ /// </summary>
+ Sha1,
+ /// <summary>
+ /// Hash Algorithm SHA256
+ /// </summary>
+ Sha256,
+ /// <summary>
+ /// Hash Algorithm SHA384
+ /// </summary>
+ Sha384,
+ /// <summary>
+ /// Hash Algorithm SHA512
+ /// </summary>
+ Sha512
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A class holding parameters for RSA algorithm with OAEP mode.
+ /// </summary>
+ public class RsaOaepParameters : CipherParameters
+ {
+ /// <summary>
+ /// A default constructor
+ /// </summary>
+ /// <remarks>The CipherAlgorithmType in CipherParameters is set to CipherAlgorithmType.RsaOaep.</remarks>
+ public RsaOaepParameters() : base(CipherAlgorithmType.RsaOaep)
+ {
+ }
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// Enumeration for RSA padding algorithm
+ /// </summary>
+ public enum RsaPaddingAlgorithm : int
+ {
+ /// <summary>
+ /// No Padding
+ /// </summary>
+ None = 0,
+ /// <summary>
+ /// PKCS#1 Padding
+ /// </summary>
+ Pkcs1,
+ /// <summary>
+ /// X9.31 padding
+ /// </summary>
+ X931
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A class holding parameters for RSA signature algorithm.
+ /// </summary>
+ public class RsaSignatureParameters : SignatureParameters
+ {
+ /// <summary>
+ /// A default constructor
+ /// </summary>
+ /// <remarks>The SignatureAlgorithmType in SignatureParameters is set to SignatureAlgorithmType.RsaSignature.</remarks>
+ /// <remarks>The RsaPadding is set to RsaPaddingAlgorithm.None.</remarks>
+ public RsaSignatureParameters() : base(SignatureAlgorithmType.RsaSignature)
+ {
+ }
+
+ /// <summary>
+ /// RSA padding algorithm
+ /// </summary>
+ public RsaPaddingAlgorithm RsaPadding
+ {
+ get { return (RsaPaddingAlgorithm)Get(SignatureParameterName.RsaPaddingAlgorithm); }
+ set { Add(SignatureParameterName.RsaPaddingAlgorithm, (int)value); }
+ }
+ }
+}
--- /dev/null
+using System;
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// This class provides the methods creating and verifying a signature.
+ /// </summary>
+ public class Signature
+ {
+ private SignatureParameters _parameters;
+
+ /// <summary>
+ /// A constructor of Signature that takes the algorithm specific parameters.
+ /// </summary>
+ /// <param name="parameters">The algorithm specific parameters.</param>
+ public Signature(SignatureParameters parameters)
+ {
+ _parameters = parameters;
+ }
+
+ /// <summary>
+ /// The algorithm specific parameters.
+ /// </summary>
+ public SignatureParameters Parameters
+ {
+ get { return _parameters; }
+ }
+
+ /// <summary>
+ /// Creates a signature on a given message using a private key and returns the signature.
+ /// </summary>
+ /// <param name="privateKeyAlias">The name of private key.</param>
+ /// <param name="password">The password used in decrypting a private key value.</param>
+ /// <param name="message.">The message that is signed with a private key.</param>
+ /// <returns>A newly created signature.</returns>
+ /// <remarks>The key type specified by privateKeyAlias should be compatible with the algorithm specified in Parameters.</remarks>
+ /// <remarks>If password of policy is provided during storing a key, the same password should be provided.</remarks>
+ public byte[] Sign(string privateKeyAlias, string password, byte[] message)
+ {
+ int hash = (int)HashAlgorithm.None;
+ try
+ {
+ hash = (int)Parameters.Get(SignatureParameterName.HashAlgorithm);
+ }
+ catch { }
+
+ int rsaPadding = (int)RsaPaddingAlgorithm.None;
+ try
+ {
+ rsaPadding = (int)Parameters.Get(SignatureParameterName.RsaPaddingAlgorithm);
+ }
+ catch { }
+
+ IntPtr ptrSignature = new IntPtr();
+ Interop.CkmcRawBuffer messageBuff = new Interop.CkmcRawBuffer(new PinnedObject(message), message.Length);
+
+ int ret = Interop.CkmcManager.CkmcCreateSignature(privateKeyAlias, password, messageBuff,
+ hash, rsaPadding, out ptrSignature);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to generate signature");
+
+ return new SafeRawBufferHandle(ptrSignature).Data;
+ }
+
+ /// <summary>
+ /// Verifies a given signature on a given message using a public key and returns the signature status.
+ /// </summary>
+ /// <param name="publicKeyAlias">The name of public key.</param>
+ /// <param name="password">The password used in decrypting a public key value.</param>
+ /// <param name="message.">The input on which the signature is created.</param>
+ /// <param name="signature.">The signature that is verified with public key.</param>
+ /// <returns>The signature statue. True is returned when the signature is valid</returns>
+ /// <remarks>The key type specified by publicKeyAlias should be compatible with the algorithm specified in Parameters.</remarks>
+ /// <remarks>If password of policy is provided during storing a key, the same password should be provided.</remarks>
+ public bool Verify(string publicKeyAlias, string password, byte[] message, byte[] signature)
+ {
+ int hash = (int)HashAlgorithm.None;
+ try
+ {
+ hash = (int)Parameters.Get(SignatureParameterName.HashAlgorithm);
+ }
+ catch { }
+
+ int rsaPadding = (int)RsaPaddingAlgorithm.None;
+ try
+ {
+ rsaPadding = (int)Parameters.Get(SignatureParameterName.RsaPaddingAlgorithm);
+ }
+ 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.CkmcVerifySignature(publicKeyAlias, password, messageBuff,
+ signatureBuff, hash, rsaPadding);
+ if (ret == (int)Interop.KeyManagerError.VerificationFailed)
+ return false;
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to verify signature");
+
+ return true;
+ }
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// Enumeration for signature algorithm types.
+ /// </summary>
+ public enum SignatureAlgorithmType : int
+ {
+ /// <summary>
+ /// RSA signature algorithm
+ /// </summary>
+ RsaSignature = 0x01,
+ /// <summary>
+ /// DSA signature algorithm
+ /// </summary>
+ DsaSignature,
+ /// <summary>
+ /// ECDSA signature algorithm
+ /// </summary>
+ EcdsaSignature
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// Enumeration for signature algorithm parameters.
+ /// </summary>
+ internal enum SignatureParameterName : int
+ {
+ /// <summary>
+ /// Signaturea Algorithm Type
+ /// </summary>
+ AlgorithmType = 0x01,
+ /// <summary>
+ /// Hash Algorithm Type
+ /// </summary>
+ HashAlgorithm,
+ /// <summary>
+ /// RSA Padding Algorithm Type
+ /// </summary>
+ RsaPaddingAlgorithm
+ }
+}
--- /dev/null
+using System;
+using System.Collections;
+
+namespace Tizen.Security.SecureRepository.Crypto
+{
+ /// <summary>
+ /// A abstract class holding parameters for signing and verification.
+ /// </summary>
+ abstract public class SignatureParameters
+ {
+ private Hashtable _parameters;
+
+ /// <summary>
+ /// A constructor with algorithm
+ /// </summary>
+ /// <param name="algorithm">An algorithm that this parameters are prepared for.</param>
+ protected SignatureParameters(SignatureAlgorithmType algorithm)
+ {
+ _parameters = new Hashtable();
+ Add(SignatureParameterName.AlgorithmType, (int)algorithm);
+ }
+
+ /// <summary>
+ /// Signature algorithm type.
+ /// </summary>
+ public SignatureAlgorithmType SignatureAlgorithm
+ {
+ get { return (SignatureAlgorithmType)Get(SignatureParameterName.AlgorithmType); }
+ }
+
+ /// <summary>
+ /// Hash algorithm used in signing anve verification.
+ /// </summary>
+ public HashAlgorithm HashAlgorithm
+ {
+ get { return (HashAlgorithm)Get(SignatureParameterName.HashAlgorithm); }
+ set { Add(SignatureParameterName.HashAlgorithm, (int)value); }
+ }
+
+ /// <summary>
+ /// Adds integer parameter.
+ /// </summary>
+ /// <param name="name">Parameter name.</param>
+ /// <param name="value">Parameter value.</param>
+ internal void Add(SignatureParameterName name, int value)
+ {
+ _parameters.Add((int)name, value);
+ }
+
+ /// <summary>
+ /// Gets integer parameter.
+ /// </summary>
+ /// <param name="name">Parameter name.</param>
+ internal int Get(SignatureParameterName name)
+ {
+ if (_parameters.ContainsKey((int)name))
+ return (int)_parameters[(int)name];
+ else
+ throw new ArgumentException("No parameter for a given SignatureParameterName ");
+ }
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// Enumeration for data format
+ /// </summary>
+ public enum DataFormat : int
+ {
+ /// <summary>
+ /// DER format base64 encoded data
+ /// </summary>
+ DerBase64 = 0,
+ /// <summary>
+ /// DER encoded data
+ /// </summary>
+ Der,
+ /// <summary>
+ /// PEM encoded data. It consists of the DER format base64 encoded
+ /// with additional header and footer lines.
+ /// </summary>
+ Pem
+ }
+}
--- /dev/null
+using System;
+using System.Collections.Generic;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// This class provides the methods storing and retrieving data.
+ /// </summary>
+ public class DataManager : Manager
+ {
+ /// <summary>
+ /// Gets data from secure repository.
+ /// </summary>
+ /// <param name="alias">The name of a certificate to retrieve.</param>
+ /// <param name="password">The password used in decrypting a data value.
+ /// If password of policy is provided in SaveData(), the same password should be provided
+ /// </param>
+ /// <returns>data specified by alias.</returns>
+ static public byte[] GetData(string alias, string password)
+ {
+ IntPtr ptr = new IntPtr();
+
+ int ret = Interop.CkmcManager.CkmcGetData(alias, password, out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get certificate. alias=" + alias);
+
+ return new SafeRawBufferHandle(ptr).Data;
+ }
+
+ /// <summary>
+ /// Gets all alias of data which the client can access.
+ /// </summary>
+ /// <returns>all alias of data which the client can access.</returns>
+ static public IEnumerable<string> GetDataAliases()
+ {
+ IntPtr ptr = new IntPtr();
+ int ret = Interop.CkmcManager.CkmcGetDataAliasList(out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get data aliases");
+
+ return new SafeAliasListHandle(ptr).Aliases;
+ }
+
+ /// <summary>
+ /// Stores data inside secure repository based on the provided policy.
+ /// </summary>
+ /// <param name="alias">The name of data to be stored.</param>
+ /// <param name="data">The binary value to be stored.</param>
+ /// <param name="policy">The policy about how to store data securely.</param>
+ static public void SaveData(string alias, byte[] data, Policy policy)
+ {
+ Interop.CkmcRawBuffer rawBuff = new Interop.CkmcRawBuffer(new PinnedObject(data), data.Length);
+
+ int ret = Interop.CkmcManager.CkmcSaveData(alias, rawBuff, policy.ToCkmcPolicy());
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to save data. alias=" + alias);
+ }
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// Enumeration for elliptic curve
+ /// </summary>
+ public enum EllipticCurveType : int
+ {
+ /// <summary>
+ /// Elliptic curve domain "secp192r1" listed in "SEC 2" recommended elliptic curve domain
+ /// </summary>
+ Prime192V1 = 0,
+ /// <summary>
+ /// "SEC 2" recommended elliptic curve domain - secp256r1
+ /// </summary>
+ Prime256V1,
+ /// <summary>
+ /// NIST curve P-384(covers "secp384r1", the elliptic curve domain listed in See SEC 2
+ /// </summary>
+ Secp384R1
+ }
+}
--- /dev/null
+using System;
+using System.Runtime.InteropServices;
+using static Interop;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// Class that represents a key.
+ /// </summary>
+ public class Key : SafeHandle
+ {
+ /// <summary>
+ /// A constructor of Key that takes the binary, its type, and optional password of binary.
+ /// </summary>
+ /// <param name="binary">The binary value of a key. This binary may be encrypted with binaryPassword.</param>
+ /// <param name="type">The key's type.</param>
+ /// <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)
+ {
+ this.SetHandle(IntPtr.Zero);
+ Binary = binary;
+ Type = type;
+ BinaryPassword = binaryPassword;
+ }
+
+ internal Key(IntPtr ptr, bool ownsHandle = true) : base(IntPtr.Zero, ownsHandle)
+ {
+ base.SetHandle(ptr);
+
+ CkmcKey ckmcKey = (CkmcKey)Marshal.PtrToStructure(handle, typeof(CkmcKey));
+ Binary = new byte[ckmcKey.size];
+ Marshal.Copy(ckmcKey.rawKey, Binary, 0, Binary.Length);
+ Type = (KeyType)ckmcKey.keyType;
+ BinaryPassword = Marshal.PtrToStringAuto(ckmcKey.password);
+ }
+
+ /// <summary>
+ /// The binary value of a key.
+ /// </summary>
+ public byte[] Binary
+ {
+ get; set;
+ }
+
+ /// <summary>
+ /// The key's type.
+ /// </summary>
+ public KeyType Type
+ {
+ get; set;
+ }
+
+ /// <summary>
+ /// The password used to decrypt binary when binary is encrypted. It's optional.
+ /// </summary>
+ public string BinaryPassword
+ {
+ get; set;
+ }
+
+ internal CkmcKey ToCkmcKey()
+ {
+ return new Interop.CkmcKey(new PinnedObject(Binary),
+ Binary.Length,
+ (int)Type,
+ new PinnedObject(BinaryPassword));
+ }
+
+ /// <summary>
+ /// Gets a value that indicates whether the handle is invalid.
+ /// </summary>
+ public override bool IsInvalid
+ {
+ get { return 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()
+ {
+ if (IsInvalid) // do not release
+ return true;
+
+ Interop.CkmcTypes.CkmcKeyFree(handle);
+ this.SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+}
--- /dev/null
+using System;
+using System.Collections.Generic;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// This class provides the methods storing, retrieving, and creating keys.
+ /// </summary>
+ public class KeyManager : Manager
+ {
+ /// <summary>
+ /// Gets a key from secure repository.
+ /// </summary>
+ /// <param name="alias">The name of a key to retrieve.</param>
+ /// <param name="password">The password used in decrypting a key value.
+ /// If password of policy is provided in SaveKey(), the same password should be provided
+ /// </param>
+ /// <returns>A key specified by alias.</returns>
+ static public Key GetKey(string alias, string password)
+ {
+ IntPtr ptr = new IntPtr();
+
+ int ret = Interop.CkmcManager.CkmcGetKey(alias, password, out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get key. alias=" + alias);
+
+ return new Key(ptr);
+ }
+
+ /// <summary>
+ /// Gets all alias of keys which the client can access.
+ /// </summary>
+ /// <returns>all alias of keys which the client can access.</returns>
+ static public IEnumerable<string> GetKeyAliases()
+ {
+ IntPtr ptr = new IntPtr();
+ int ret = Interop.CkmcManager.CkmcGetKeyAliasList(out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get key aliases.");
+
+ return new SafeAliasListHandle(ptr).Aliases;
+ }
+
+ /// <summary>
+ /// Stores a key inside secure repository based on the provided policy.
+ /// </summary>
+ /// <param name="alias">The name of a key to be stored.</param>
+ /// <param name="key">The key's binary value to be stored.</param>
+ /// <param name="policy">The policy about how to store a key securely.</param>
+ /// <remarks>Type in key may be set to KeyType.None as an input. Type is determined inside secure reposioty during storing keys.</remarks>
+ /// <remarks>If password in policy is provided, the key is additionally encrypted with the password in policy.</remarks>
+ static public void SaveKey(string alias, Key key, Policy policy)
+ {
+ int ret = Interop.CkmcManager.CkmcSaveKey(alias, key.ToCkmcKey(), policy.ToCkmcPolicy());
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to save Key. alias=" + alias);
+ }
+
+ /// <summary>
+ /// Creates RSA private/public key pair and stores them inside secure repository based on each policy.
+ /// </summary>
+ /// <param name="size">The size of key strength to be created. 1024, 2048, 3072, and 4096 are supported.</param>
+ /// <param name="privateKeyAlias">The name of private key to be stored.</param>
+ /// <param name="publicKeyAlias">The name of public key to be stored.</param>
+ /// <param name="privateKeyPolicy">The policy about how to store a private key securely.</param>
+ /// <param name="publicKeyPolicy">The policy about how to store a public key securely.</param>
+ /// <remarks>If password in policy is provided, the key is additionally encrypted with the password in policy.</remarks>
+ static public void CreateKeyPairRsa(int size, string privateKeyAlias, string publicKeyAlias,
+ Policy privateKeyPolicy, Policy publicKeyPolicy)
+ {
+ int ret = Interop.CkmcManager.CkmcCreateKeyPairRsa(size, privateKeyAlias, publicKeyAlias,
+ privateKeyPolicy.ToCkmcPolicy(), publicKeyPolicy.ToCkmcPolicy());
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to Create RSA Key Pair");
+ }
+
+ /// <summary>
+ /// Creates DSA private/public key pair and stores them inside secure repository based on each policy.
+ /// </summary>
+ /// <param name="size">The size of key strength to be created. 1024, 2048, and 4096 are supported.</param>
+ /// <param name="privateKeyAlias">The name of private key to be stored.</param>
+ /// <param name="publicKeyAlias">The name of public key to be stored.</param>
+ /// <param name="privateKeyPolicy">The policy about how to store a private key securely.</param>
+ /// <param name="publicKeyPolicy">The policy about how to store a public key securely.</param>
+ /// <remarks>If password in policy is provided, the key is additionally encrypted with the password in policy.</remarks>
+ static public void CreateKeyPairDsa(int size, string privateKeyAlias, string publicKeyAlias,
+ Policy privateKeyPolicy, Policy publicKeyPolicy)
+ {
+ int ret = Interop.CkmcManager.CkmcCreateKeyPairDsa(size, privateKeyAlias, publicKeyAlias,
+ privateKeyPolicy.ToCkmcPolicy(), publicKeyPolicy.ToCkmcPolicy());
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to Create DSA Key Pair");
+ }
+
+ /// <summary>
+ /// Creates ECDSA private/public key pair and stores them inside secure repository based on each policy.
+ /// </summary>
+ /// <param name="type">The type of elliptic curve of ECDSA.</param>
+ /// <param name="privateKeyAlias">The name of private key to be stored.</param>
+ /// <param name="publicKeyAlias">The name of public key to be stored.</param>
+ /// <param name="privateKeyPolicy">The policy about how to store a private key securely.</param>
+ /// <param name="publicKeyPolicy">The policy about how to store a public key securely.</param>
+ /// <remarks>If password in policy is provided, the key is additionally encrypted with the password in policy.</remarks>
+ static public void CreateKeyPairEcdsa(EllipticCurveType type, string privateKeyAlias, string publicKeyAlias,
+ Policy privateKeyPolicy, Policy publicKeyPolicy)
+ {
+ int ret = Interop.CkmcManager.CkmcCreateKeyPairEcdsa((int)type, privateKeyAlias, publicKeyAlias,
+ privateKeyPolicy.ToCkmcPolicy(), publicKeyPolicy.ToCkmcPolicy());
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to Create ECDSA Key Pair");
+ }
+
+ /// <summary>
+ /// Creates AES key and stores it inside secure repository based on each policy.
+ /// </summary>
+ /// <param name="size">The size of key strength to be created. 128, 192 and256 are supported.</param>
+ /// <param name="keyAlias">The name of key to be stored.</param>
+ /// <param name="policy">The policy about how to store the key securely.</param>
+ /// <remarks>If password in policy is provided, the key is additionally encrypted with the password in policy.</remarks>
+ static public void CreateKeyAes(int size, string keyAlias, Policy policy)
+ {
+ int ret = Interop.CkmcManager.CkmcCreateKeyAes(size, keyAlias, policy.ToCkmcPolicy());
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to AES Key");
+ }
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// Enumeration for key types of key manager.
+ /// </summary>
+ public enum KeyType : int
+ {
+ /// <summary>
+ /// Key type not specified
+ /// </summary>
+ None = 0,
+ /// <summary>
+ /// RSA public key
+ /// </summary>
+ RsaPublic,
+ /// <summary>
+ /// RSA private key
+ /// </summary>
+ RsaPrivate,
+ /// <summary>
+ /// ECDSA public key
+ /// </summary>
+ EcdsaPublic,
+ /// <summary>
+ /// ECDSA private key
+ /// </summary>
+ EcdsaPrivate,
+ /// <summary>
+ /// DSA public key
+ /// </summary>
+ DsaPublic,
+ /// <summary>
+ /// DSA private key
+ /// </summary>
+ DsaPrivate,
+ /// <summary>
+ /// AES key
+ /// </summary>
+ Aes
+ }
+}
--- /dev/null
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// This class is a base class of XxxManager classes. It provides the common methods for all sub classes.
+ /// </summary>
+ public class Manager
+ {
+ // ckmc_owner_id_separator
+ // ckmc_owner_id_system
+
+ /// <summary>
+ /// Separator between alias and owner id.
+ /// </summary>
+ /// <remarks>
+ /// Alias can be provided as an alias alone, or together with owner id.
+ /// In this case, separator " " (space bar) is used to separate id and alias.
+ /// </remarks>
+ public const string OwnerIdSeperator = " ";
+
+ /// <summary>
+ /// The owner of system database.
+ /// </summary>
+ /// <remarks>
+ /// SystemOwnerId constains id connected with all SYSTEM applications that run
+ /// with uid less than 5000.
+ /// Client should use SystemOwnerId to access data owned by system application
+ /// and stored in system database.
+ /// Note: Client must have permission to access proper row.
+ /// </remarks>
+ public const string SystemOwnerId = "/System";
+
+ /// <summary>
+ /// Removes a an entry (no matter of type) from the key manager.
+ /// </summary>
+ /// <param name="alias">Item alias to be removed.</param>
+ /// <remarks>To remove item, client must have remove permission to the specified item.</remarks>
+ /// <remarks>The item owner can remove by default.</remarks>
+ static public void RemoveAlias(string alias)
+ {
+ int ret = Interop.CkmcManager.CkmcRemoveAlias(alias);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to remove alias. alias=" + alias);
+ }
+
+ /// <summary>
+ /// Allows another application to access client's application data.
+ /// </summary>
+ /// <param name="alias">Item alias for which access will be granted.</param>
+ /// <param name="otherPackageId">Package id of the application that will gain access rights.</param>
+ /// <param name="permissions">Mask of permissions(Permission enum) granted for an application with otherPackageId.</param>
+ /// <remarks>Data identified by alias should exist.</remarks>
+ /// <remarks>The item owner can set permissions.</remarks>
+ static public void SetPermission(string alias, string otherPackageId, int permissions)
+ {
+ int ret = Interop.CkmcManager.CkmcSetPermission(alias, otherPackageId, permissions);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to set permission. alias=" + alias);
+ }
+ }
+}
--- /dev/null
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// Enumeration for OCSP status.
+ /// </summary>
+ public enum OcspStatus : int
+ {
+ /// <summary>
+ /// OCSP status is good
+ /// </summary>
+ Good = 0x00,
+ /// <summary>
+ /// The certificate is revoked
+ /// </summary>
+ Revoked = 0x01,
+ /// <summary>
+ /// Unknown error
+ /// </summary>
+ Unknown = 0x02,
+ /// <summary>
+ /// The certificate does not provide OCSP extension
+ /// </summary>
+ Unsupported = 0x03,
+ /// <summary>
+ /// The invalid URL in certificate OCSP extension
+ /// </summary>
+ InvalidUrl = 0x04,
+ /// <summary>
+ /// The invalid response from OCSP server
+ /// </summary>
+ InvalidResponse = 0x05,
+ /// <summary>
+ /// OCSP remote server error
+ /// </summary>
+ RemoteError = 0x06,
+ /// <summary>
+ /// Network connection error
+ /// </summary>
+ NetworkError = 0x07,
+ /// <summary>
+ /// Internal error
+ /// </summary>
+ InternalError = 0x08
+ }
+}
--- /dev/null
+namespace Tizen.Security.SecureRepository
+{
+
+ /// <summary>
+ /// Enumeration for permissions to access/modify alias.
+ /// </summary>
+ public enum Permission : int
+ {
+ /// <summary>
+ /// Clear permissions
+ /// </summary>
+ None = 0x00,
+ /// <summary>
+ /// Eead allowed
+ /// </summary>
+ Read = 0x01,
+ /// <summary>
+ /// Remove allowed
+ /// </summary>
+ Remove = 0x02
+ }
+}
--- /dev/null
+using System;
+using System.Runtime.InteropServices;
+
+namespace Tizen.Security.SecureRepository
+{
+ internal class PinnedObject : IDisposable
+ {
+ private bool _disposed = false;
+ private GCHandle _pinnedObj;
+
+ public PinnedObject(Object obj)
+ {
+ _pinnedObj = GCHandle.Alloc(obj, GCHandleType.Pinned);
+ }
+
+ ~PinnedObject()
+ {
+ Dispose(false);
+ }
+
+ public static implicit operator IntPtr(PinnedObject pinned)
+ {
+ return pinned._pinnedObj.AddrOfPinnedObject();
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+ _pinnedObj.Free();
+ _disposed = true;
+ }
+ }
+}
--- /dev/null
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using static Interop;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// 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
+ {
+ /// <summary>
+ /// Creates a new Pkcs12from a given PKCS#12 file and returns it.
+ /// </summary>
+ /// <param name="filePath">The path of PKCS12 file to be loaded.</param>
+ /// <param name="filePassword">The passphrase used to decrypt the PCKS12 file.
+ /// If PKCS12 file is not encrypted, passphrase can be null.</param>
+ static public Pkcs12 LoadPkcs12(string filePath, string filePassword)
+ {
+ IntPtr ptr = new IntPtr();
+
+ int ret = Interop.CkmcTypes.CkmcPkcs12Load(filePath, filePassword, out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to load PKCS12. file=" + filePath);
+
+ return new Pkcs12(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)
+ {
+ this.SetHandle(IntPtr.Zero);
+
+ this.PrivateKey = privateKey;
+ this.Certificate = null;
+ this.CaChain = null;
+ }
+
+ /// <summary>
+ /// A constructor of Key that takes a private key and its corresponding certicate.
+ /// </summary>
+ /// <param name="privateKey">A private key.</param>
+ /// <param name="certificate">A certificate corresponding the private key</param>
+ public Pkcs12(Key privateKey, Certificate certificate) : base(IntPtr.Zero, true)
+ {
+ this.SetHandle(IntPtr.Zero);
+
+ this.PrivateKey = privateKey;
+ this.Certificate = certificate;
+ this.CaChain = null;
+ }
+
+ /// <summary>
+ /// A constructor of Key that takes a private key, its corresponding certicate, and CA's certificate chain.
+ /// </summary>
+ /// <param name="privateKey">A private key.</param>
+ /// <param name="certificate">A certificate corresponding the private key</param>
+ /// <param name="caChain">A certificate chain of CA(Certificate Authority) that issued the certificate.</param>
+ public Pkcs12(Key privateKey, Certificate certificate, IEnumerable<Certificate> caChain) : base(IntPtr.Zero, true)
+ {
+ this.SetHandle(IntPtr.Zero);
+
+ this.PrivateKey = privateKey;
+ this.Certificate = certificate;
+ this.CaChain = caChain;
+ }
+
+ internal Pkcs12(IntPtr ptrCkmcPkcs12, bool ownsHandle = true) : base(IntPtr.Zero, ownsHandle)
+ {
+ this.SetHandle(ptrCkmcPkcs12);
+
+ CkmcPkcs12 ckmcPkcs12 = (CkmcPkcs12)Marshal.PtrToStructure(handle, typeof(CkmcPkcs12));
+ this.PrivateKey = new Key(ckmcPkcs12.privateKey, false);
+ if (ckmcPkcs12.certificate != IntPtr.Zero)
+ this.Certificate = new Certificate(ckmcPkcs12.certificate, false);
+ if (ckmcPkcs12.caChain != IntPtr.Zero)
+ this.CaChain = new SafeCertificateListHandle(ckmcPkcs12.caChain, false).Certificates;
+ }
+
+ /// <summary>
+ /// A private key.
+ /// </summary>
+ public Key PrivateKey
+ {
+ get; set;
+ }
+
+ /// <summary>
+ /// A certificate corresponding the private key.
+ /// </summary>
+ public Certificate Certificate
+ {
+ get; set;
+ }
+
+ /// <summary>
+ /// A certificate chain of CA(Certificate Authority) that issued the certificate.
+ /// </summary>
+ public IEnumerable<Certificate> CaChain
+ {
+ get; set;
+ }
+
+ internal CkmcPkcs12 ToCkmcPkcs12()
+ {
+ Interop.CkmcKey ckmcKey = new Interop.CkmcKey(new PinnedObject(PrivateKey.Binary),
+ PrivateKey.Binary.Length,
+ (int)PrivateKey.Type,
+ new PinnedObject(PrivateKey.BinaryPassword));
+ Interop.CkmcCert ckmcCert = new Interop.CkmcCert(new PinnedObject(Certificate.Binary),
+ Certificate.Binary.Length,
+ (int)Certificate.Format);
+ SafeCertificateListHandle ckmcCaCerts = new SafeCertificateListHandle(CaChain);
+
+ return new Interop.CkmcPkcs12(new PinnedObject(ckmcKey),
+ new PinnedObject(ckmcCert),
+ ckmcCaCerts.ToCkmcCertificateListPtr());
+ }
+
+ /// <summary>
+ /// Gets a value that indicates whether the handle is invalid.
+ /// </summary>
+ public override bool IsInvalid
+ {
+ get { return 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()
+ {
+ if (IsInvalid) // do not release
+ return true;
+
+ Interop.CkmcTypes.CkmcPkcs12Free(handle);
+ this.SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+}
--- /dev/null
+using System;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// This class provides the methods storing, retrieving Pkcs12 contents.
+ /// </summary>
+ public class Pkcs12Manager : Manager
+ {
+ /// <summary>
+ /// Gets Pkcs12 contents from secure repository.
+ /// </summary>
+ /// <param name="alias">The name of data to retrieve.</param>
+ /// <param name="keyPassword">The password used in decrypting a private key value.
+ /// If password of keyPolicy is provided in SavePkcs12(), the same password should be provided
+ /// </param>
+ /// <param name="cerificatePassword">The password used in decrypting a certificate value.
+ /// If password of certificatePolicy is provided in SavePkcs12(), the same password should be provided
+ /// </param>
+ /// <returns>A Pkcs12 data specified by alias.</returns>
+ static public Pkcs12 GetPkcs12(string alias, string keyPassword, string cerificatePassword)
+ {
+ IntPtr ptr = new IntPtr();
+
+ int ret = Interop.CkmcManager.CkmcGetPkcs12(alias, keyPassword, cerificatePassword, out ptr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to get PKCS12. alias=" + alias);
+
+ return new Pkcs12(ptr);
+ }
+
+ /// <summary>
+ /// Stores PKCS12's contents inside key manager based on the provided policies.
+ /// All items from the PKCS12 will use the same alias.
+ /// </summary>
+ /// <param name="alias">The name of a data to be stored.</param>
+ /// <param name="pkcs12">The pkcs12 data to be stored.</param>
+ /// <param name="keyPolicy">The policy about how to store pkcs's private key.</param>
+ /// <param name="certificatePolicy">The policy about how to store pkcs's certificate.</param>
+ static public void SavePkcs12(string alias, Pkcs12 pkcs12, Policy keyPolicy, Policy certificatePolicy)
+ {
+ int ret = Interop.CkmcManager.CkmcSavePkcs12(alias,
+ new PinnedObject(pkcs12.ToCkmcPkcs12()),
+ keyPolicy.ToCkmcPolicy(),
+ certificatePolicy.ToCkmcPolicy());
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to save PKCS12. alias=" + alias);
+ }
+ }
+}
--- /dev/null
+using System;
+using static Interop;
+
+namespace Tizen.Security.SecureRepository
+{
+ /// <summary>
+ /// A class for a policy for storing key, certificate, and binary data.
+ /// </summary>
+ public class Policy
+ {
+ /// <summary>
+ /// A default constructor of Policy with default policy.
+ /// </summary>
+ /// <remarks>The default value for Password is null and the default value for Extractabl is false.</remarks>
+ public Policy()
+ {
+ Password = null;
+ Extractable = true;
+ }
+
+ /// <summary>
+ /// A constructor of Key that takes the flag for extractable.
+ /// </summary>
+ /// <param name="extractable">If true key may be extracted from secure repository.</param>
+ /// <remarks>The default value for Password is null.</remarks>
+ public Policy(bool extractable)
+ {
+ Password = null;
+ Extractable = extractable;
+ }
+
+ /// <summary>
+ /// A constructor of Key that takes the password.
+ /// </summary>
+ /// <param name="password">Used to encrypt data secure repository.</param>
+ /// <remarks>The default value for Extractabl is false.</remarks>
+ public Policy(String password)
+ {
+ Password = password;
+ Extractable = true;
+ }
+
+ /// <summary>
+ /// A constructor of Key that takes the password and the flag for extractable.
+ /// </summary>
+ /// <param name="password">Used to encrypt data secure repository.</param>
+ /// <param name="extractable">If true key may be extracted from secure repository.</param>
+ public Policy(String password, bool extractable)
+ {
+ Password = password;
+ Extractable = extractable;
+ }
+
+ /// <summary>
+ /// Used to encrypt data secure repository. If it is not null, the data
+ /// (or key, or certificate) is stored encrypted with this password inside secure repository
+ /// </summary>
+ public String Password
+ {
+ get; set;
+ }
+
+ /// <summary>
+ /// If true key may be extracted from secure repository.
+ /// </summary>
+ public bool Extractable
+ {
+ get; set;
+ }
+
+ internal CkmcPolicy ToCkmcPolicy()
+ {
+ return new Interop.CkmcPolicy(Password, Extractable);
+ }
+ }
+}
--- /dev/null
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using static Interop;
+
+namespace Tizen.Security.SecureRepository
+{
+ internal class SafeAliasListHandle : SafeHandle
+ {
+ public SafeAliasListHandle(IntPtr ptrAliases, bool ownsHandle = true) : base(IntPtr.Zero, ownsHandle)
+ {
+ base.SetHandle(ptrAliases);
+
+ List<string> aliases = new List<string>();
+ while (ptrAliases != IntPtr.Zero)
+ {
+ CkmcAliasList ckmcAliasList = (CkmcAliasList)Marshal.PtrToStructure(ptrAliases, typeof(CkmcAliasList));
+ aliases.Add(Marshal.PtrToStringAuto(ckmcAliasList.alias));
+ ptrAliases = ckmcAliasList.next;
+ }
+
+ this.Aliases = aliases;
+ }
+
+ public List<string> Aliases
+ {
+ get; set;
+ }
+
+ /// <summary>
+ /// Gets a value that indicates whether the handle is invalid.
+ /// </summary>
+ public override bool IsInvalid
+ {
+ get { return 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()
+ {
+ if (IsInvalid) // do not release
+ return true;
+
+ Interop.CkmcTypes.CkmcAliasListAllFree(handle);
+ this.SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+}
--- /dev/null
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using static Interop;
+
+namespace Tizen.Security.SecureRepository
+{
+ internal class SafeCertificateListHandle : SafeHandle
+ {
+ private IEnumerable<Certificate> _certificates;
+
+ public SafeCertificateListHandle(IEnumerable<Certificate> certs) : base(IntPtr.Zero, true)
+ {
+ this.SetHandle(IntPtr.Zero);
+ _certificates = certs;
+ }
+
+ public SafeCertificateListHandle(IntPtr ptrCerts, bool ownsHandle = true) : base(IntPtr.Zero, ownsHandle)
+ {
+ this.SetHandle(ptrCerts);
+
+ List<Certificate> certs = new List<Certificate>();
+ IntPtr ptrCurr = handle;
+ while (ptrCurr != IntPtr.Zero)
+ {
+ CkmcCertList ckmcCertList = (CkmcCertList)Marshal.PtrToStructure(ptrCurr, typeof(CkmcCertList));
+ certs.Add(new Certificate(ckmcCertList.cert, false));
+ ptrCurr = ckmcCertList.next;
+ }
+
+ _certificates = certs;
+ }
+
+ public IEnumerable<Certificate> Certificates
+ {
+ get { return _certificates; }
+ }
+
+ internal IntPtr ToCkmcCertificateListPtr()
+ {
+ if (_certificates == null)
+ return IntPtr.Zero;
+
+ if (!IsInvalid)
+ return handle;
+
+ IntPtr first = IntPtr.Zero;
+ IntPtr previous = IntPtr.Zero;
+
+ int ret;
+ foreach (Certificate cert in _certificates)
+ {
+ IntPtr certPtr;
+ ret = Interop.CkmcTypes.CkmcCertNew(cert.Binary, (uint)cert.Binary.Length, (int)cert.Format, out certPtr);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to create new Certificate.");
+
+ IntPtr outCertList;
+ if (previous == IntPtr.Zero)
+ {
+ ret = Interop.CkmcTypes.CkmcCertListNew(certPtr, out outCertList);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to create new CertificateList.");
+ first = outCertList;
+ previous = outCertList;
+ }
+ else
+ {
+ ret = Interop.CkmcTypes.CkmcCertListAdd(previous, certPtr, out outCertList);
+ Interop.KeyManagerExceptionFactory.CheckNThrowException(ret, "Failed to add Certificate to CertificateList.");
+ previous = outCertList;
+ }
+ }
+
+ this.SetHandle(first);
+ return first;
+ }
+
+ /// <summary>
+ /// Gets a value that indicates whether the handle is invalid.
+ /// </summary>
+ public override bool IsInvalid
+ {
+ get { return (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()
+ {
+ if (handle == IntPtr.Zero) // do not release
+ return true;
+
+ Interop.CkmcTypes.CkmcCertListAllFree(handle);
+ this.SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+}
--- /dev/null
+using System;
+using System.Runtime.InteropServices;
+using static Interop;
+
+namespace Tizen.Security.SecureRepository
+{
+ internal class SafeRawBufferHandle : SafeHandle
+ {
+ public SafeRawBufferHandle(IntPtr ptrRawBuffer, bool ownsHandle = true) : base(IntPtr.Zero, true)
+ {
+ this.SetHandle(ptrRawBuffer);
+
+ if (ptrRawBuffer == IntPtr.Zero)
+ return;
+
+ CkmcRawBuffer buff = (CkmcRawBuffer)Marshal.PtrToStructure(ptrRawBuffer, typeof(CkmcRawBuffer));
+ byte[] data = new byte[buff.size];
+ Marshal.Copy(buff.data, data, 0, data.Length);
+
+ this.Data = data;
+ }
+
+ public byte[] Data
+ {
+ get; set;
+ }
+
+ /// <summary>
+ /// Gets a value that indicates whether the handle is invalid.
+ /// </summary>
+ public override bool IsInvalid
+ {
+ get { return 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()
+ {
+ if (IsInvalid) // do not release
+ return true;
+
+ Interop.CkmcTypes.CkmcBufferFree(handle);
+ this.SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>Tizen.Security</AssemblyName>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ <ProductVersion>10.0.0</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{0EA0E64F-637A-480A-8746-4ACC1B0FE022}</ProjectGuid>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <DocumentationFile>bin\Debug\Tizen.Security.XML</DocumentationFile>
+ <CodeAnalysisRuleSet>ExtendedDesignGuidelineRules.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup>
+ <SignAssembly>true</SignAssembly>
+ </PropertyGroup>
+ <PropertyGroup>
+ <AssemblyOriginatorKeyFile>Tizen.Security.snk</AssemblyOriginatorKeyFile>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Net.Http" />
+ <Reference Include="System.Xml" />
+ <Reference Include="Tizen.Internals">
+ <HintPath>..\..\tizen\Tizen.Internals\bin\Debug\Tizen.Internals.dll</HintPath>
+ </Reference>
+ <Reference Include="Tizen">
+ <HintPath>..\..\tizen\Tizen\bin\Debug\Tizen.dll</HintPath>
+ </Reference>
+ <!-- <Reference Include="Tizen.Applications">
+ <HintPath>..\..\application\Tizen.Applications\bin\Debug\Tizen.Applications.dll</HintPath>
+ </Reference> -->
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Interop\Interop.CkmcErrors.cs" />
+ <Compile Include="Interop\Interop.CkmcManager.cs" />
+ <Compile Include="Interop\Interop.CkmcTypes.cs" />
+ <Compile Include="Interop\Interop.Libraries.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Certificate.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\CertificateManager.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\AesCbcCipherParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\AesCfbCipherParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\AesCipherParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\AesCtrCipherParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\AesGcmCipherParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\Cipher.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\CipherAlgorithmType.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\CipherParameterName.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\CipherParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\DsaSignatureParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\EcdsaSignatureParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\HashAlgorithm.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\RsaOaepParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\RsaPaddingAlgorithm.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\RsaSignatureParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\Signature.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\SignatureAlgorithmType.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\SignatureParameterName.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Crypto\SignatureParameters.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\DataFormat.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\DataManager.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\EllipticCurveType.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Key.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\KeyManager.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\KeyType.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Manager.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\OcspStatus.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Permission.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\PinnedObject.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Pkcs12.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Pkcs12Manager.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\Policy.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\SafeAliasListHandle.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\SafeCertificateListHandle.cs" />
+ <Compile Include="Tizen.Security.SecureRepository\SafeRawBufferHandle.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="Tizen.Security.snk" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <ProjectView>ShowAllFiles</ProjectView>
+ </PropertyGroup>
+</Project>
\ No newline at end of file
--- /dev/null
+\r
+Microsoft Visual Studio Solution File, Format Version 11.00\r
+# Visual Studio 2010\r
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tizen.Security", "Tizen.Security.csproj", "{663C5A3D-E631-4987-AEE7-F498C56A40FC}"\r
+EndProject\r
+Global\r
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
+ Debug|Any CPU = Debug|Any CPU\r
+ Release|Any CPU = Release|Any CPU\r
+ EndGlobalSection\r
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
+ {663C5A3D-E631-4987-AEE7-F498C56A40FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r
+ {663C5A3D-E631-4987-AEE7-F498C56A40FC}.Debug|Any CPU.Build.0 = Debug|Any CPU\r
+ {663C5A3D-E631-4987-AEE7-F498C56A40FC}.Release|Any CPU.ActiveCfg = Release|Any CPU\r
+ {663C5A3D-E631-4987-AEE7-F498C56A40FC}.Release|Any CPU.Build.0 = Release|Any CPU\r
+ EndGlobalSection\r
+ GlobalSection(MonoDevelopProperties) = preSolution\r
+ StartupItem = Tizen.Security.csproj\r
+ EndGlobalSection\r
+EndGlobal\r
--- /dev/null
+<Properties>
+ <MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" />
+ <MonoDevelop.Ide.Workbench />
+ <MonoDevelop.Ide.DebuggingService.Breakpoints>
+ <BreakpointStore />
+ </MonoDevelop.Ide.DebuggingService.Breakpoints>
+ <MonoDevelop.Ide.DebuggingService.PinnedWatches />
+</Properties>
\ No newline at end of file