void CreateSecretKey(string storeKeyName, bool isInvalidatedByBiometricEnrollment)
        {
            try
            {
                keyStore.Load(null);
                KeyGenParameterSpec.Builder keyParamBuilder = null;
                if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    keyParamBuilder = new KeyGenParameterSpec.Builder(storeKeyName,
                                                                      KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                                      .SetBlockModes(KeyProperties.BlockModeCbc)
                                      // This key is authorized to be used only if the user has been authenticated.
                                      .SetUserAuthenticationRequired(isUserAuthenticationRequired)
                                      .SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7);
                }

                if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
                {
                    keyParamBuilder.SetInvalidatedByBiometricEnrollment(isInvalidatedByBiometricEnrollment);
                }
                if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    keyGenerator.Init(keyParamBuilder.Build());
                }
                keyGenerator.GenerateKey();
            }
            catch (Java.Lang.Exception e)
            {
                if (e is NoSuchAlgorithmException || e is InvalidAlgorithmParameterException || e is CertificateException || e is IOException)
                {
                    throw new RuntimeException("Failed to create secret key. " + e.Message, e);
                }
            }
        }
示例#2
0
        ISecretKey GetKey()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.M)
            {
                return(null);
            }

            IKey existingKey = keyStore.GetKey(alias, null);

            if (existingKey != null)
            {
                ISecretKey existingSecretKey = existingKey.JavaCast <ISecretKey>();
                return(existingSecretKey);
            }

            var keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, androidKeyStore);
            var builder      = new KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                               .SetBlockModes(KeyProperties.BlockModeGcm)
                               .SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone)
                               .SetRandomizedEncryptionRequired(false);

            keyGenerator.Init(builder.Build());

            return(keyGenerator.GenerateKey());
        }
示例#3
0
        public void CreateKeyPair()
        {
            DeleteKey();
            KeyPairGenerator keyGenerator =
                KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2 &&
                Build.VERSION.SdkInt <= BuildVersionCodes.LollipopMr1)
            {
                var calendar = Calendar.GetInstance(_context.Resources.Configuration.Locale);
                var endDate  = Calendar.GetInstance(_context.Resources.Configuration.Locale);
                endDate.Add(CalendarField.Year, 20);
                //this API is obsolete after Android M, but I am supporting Android L
#pragma warning disable 618
                var builder = new KeyPairGeneratorSpec.Builder(_context)
#pragma warning restore 618
                              .SetAlias(_keyName).SetSerialNumber(BigInteger.One)
                              .SetSubject(new X500Principal($"CN={_keyName} CA Certificate"))
                              .SetStartDate(calendar.Time)
                              .SetEndDate(endDate.Time).SetKeySize(KeySize);
                keyGenerator.Initialize(builder.Build());
            }
            else if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                var builder =
                    new KeyGenParameterSpec.Builder(_keyName, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                    .SetBlockModes(KeyProperties.BlockModeEcb)
                    .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                    .SetRandomizedEncryptionRequired(false).SetKeySize(KeySize);
                keyGenerator.Initialize(builder.Build());
            }
            keyGenerator.GenerateKeyPair();
        }
        void CreateKey()
        {
            KeyGenerator        keyGen     = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, KEYSTORE_NAME);
            KeyGenParameterSpec keyGenSpec =
                new KeyGenParameterSpec.Builder(KEY_NAME, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                .SetBlockModes(BLOCK_MODE).SetEncryptionPaddings(ENCRYPTION_PADDING)
                .SetUserAuthenticationRequired(true)
                .Build();

            keyGen.Init(keyGenSpec);
            keyGen.GenerateKey();
        }
        private void CreateNewKey(string alias)
        {
            KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Decrypt | KeyStorePurpose.Encrypt)
                                       .SetBlockModes(KeyProperties.BlockModeCbc)
                                       .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                                       .Build();

            KeyPairGenerator generator = KeyPairGenerator.GetInstance("RSA", "AndroidKeyStore");

            generator.Initialize(spec);

            generator.GenerateKeyPair();
        }
        void CreateKey()
        {
            var keyGen     = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, KeyStoreName);
            var keyGenSpec =
                new KeyGenParameterSpec.Builder(KeyName, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                .SetBlockModes(BlockMode)
                .SetEncryptionPaddings(EncryptionPadding)
                .SetUserAuthenticationRequired(true)
                .Build();

            keyGen.Init(keyGenSpec);
            keyGen.GenerateKey();
        }
        private static void GenerateKey()
        {
            var spec = new KeyGenParameterSpec.Builder(KeyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                       .SetBlockModes(BlockMode)
                       .SetEncryptionPaddings(Padding)
                       .SetUserAuthenticationRequired(true)
                       .Build();

            var generator = KeyGenerator.GetInstance(Algorithm, KeyStoreName);

            generator.Init(spec);
            generator.GenerateKey();
        }
示例#8
0
        private void CreateKey()
        {
            KeyGenerator        keyGen     = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, KeyStoreName);
            KeyGenParameterSpec keyGenSpec =
                new KeyGenParameterSpec.Builder(KeyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                .SetKeySize(256)
                .SetBlockModes(KeyProperties.BlockModeCbc)
                .SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7)
                .SetUserAuthenticationRequired(true)
                .Build();

            keyGen.Init(keyGenSpec);
            keyGen.GenerateKey();
        }
        /// <summary>
        ///     Creates the Key for fingerprint authentication.
        /// </summary>
        void CreateKey()
        {
            KeyGenerator        keyGen     = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, _keystoreName);
            KeyGenParameterSpec keyGenSpec =
                new KeyGenParameterSpec.Builder(_keyName, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                .SetBlockModes(_blockMode)
                .SetEncryptionPaddings(_encryptionPadding)
                .SetUserAuthenticationRequired(true)
                .Build();

            keyGen.Init(keyGenSpec);
            keyGen.GenerateKey();
            Logger.Debug("[CryptoHelper] New key created for fingerprint authentication.");
        }
示例#10
0
        public void SetBytes(string key, byte[] bytes)
        {
            var keyStore = KeyStore.GetInstance(KeyStoreType);

            keyStore.Load(null);

            var storeKey = keyStore.GetKey(Alias, null);

            if (storeKey == null)
            {
                var generator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, KeyStoreType);
                var spec      = new KeyGenParameterSpec.Builder(Alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                                .SetBlockModes(KeyProperties.BlockModeGcm)
                                .SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone)
                                .SetRandomizedEncryptionRequired(false)
                                .Build();

                generator.Init(spec);
                generator.GenerateKey();

                storeKey = keyStore.GetKey(Alias, null);
                if (storeKey == null)
                {
                    throw new InvalidOperationException("Failed KeyStore key generation.");
                }
            }

            var iv     = new byte[IvLength];
            var randam = new SecureRandom();

            randam.NextBytes(iv);

            var cipher = Cipher.GetInstance(CipherTransformation);

            cipher.Init(CipherMode.EncryptMode, storeKey, new GCMParameterSpec(GcmTagLength, iv));

            var encryptedBytes = cipher.DoFinal(bytes);

            var saveBytes = new byte[iv.Length + encryptedBytes.Length];

            Array.Copy(iv, 0, saveBytes, 0, iv.Length);
            Array.Copy(encryptedBytes, 0, saveBytes, iv.Length, encryptedBytes.Length);

            var saveText = Convert.ToBase64String(saveBytes);

            var edit = sharedPreferences.Edit();

            edit.PutString(key, saveText);
            edit.Commit();
        }
示例#11
0
        private void GenerateStoreKey(bool withDate)
        {
            if (_keyStore.ContainsAlias(KeyAlias))
            {
                return;
            }

            ClearSettings();

            var end = Calendar.Instance;

            end.Add(CalendarField.Year, 99);

            if (_oldAndroid)
            {
                var subject = new X500Principal($"CN={KeyAlias}");

                var builder = new KeyPairGeneratorSpec.Builder(Application.Context)
                              .SetAlias(KeyAlias)
                              .SetSubject(subject)
                              .SetSerialNumber(BigInteger.Ten);

                if (withDate)
                {
                    builder.SetStartDate(new Date(0)).SetEndDate(end.Time);
                }

                var spec = builder.Build();
                var gen  = KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, AndroidKeyStore);
                gen.Initialize(spec);
                gen.GenerateKeyPair();
            }
            else
            {
                var builder = new KeyGenParameterSpec.Builder(KeyAlias, KeyStorePurpose.Decrypt | KeyStorePurpose.Encrypt)
                              .SetBlockModes(KeyProperties.BlockModeGcm)
                              .SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone);

                if (withDate)
                {
                    builder.SetKeyValidityStart(new Date(0)).SetKeyValidityEnd(end.Time);
                }

                var spec = builder.Build();
                var gen  = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, AndroidKeyStore);
                gen.Init(spec);
                gen.GenerateKey();
            }
        }
        private void PrepareKeyStore()
        {
            _keyStore = KeyStore.GetInstance(AndroidKeyStoreKey);
            _keyStore.Load(null);

            if (_keyStore.ContainsAlias(ProtectedDataKey))
            {
                _keyStore.GetKey(ProtectedDataKey, null);
            }
            else
            {
                var context = global::Android.App.Application.Context;

                // thanks to https://dzone.com/articles/xamarin-android-asymmetric-encryption-without-any

                var keyGenerator = KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, AndroidKeyStoreKey);

                if (_sdkLessThan23)
                {
                    var calendar = Calendar.GetInstance(context.Resources.Configuration.Locale);
                    var endDate  = Calendar.GetInstance(context.Resources.Configuration.Locale);
                    endDate.Add(CalendarField.Year, 20);

#pragma warning disable 618
                    var builder = new KeyPairGeneratorSpec.Builder(context)
#pragma warning restore 618
                                  .SetAlias(ProtectedDataKey)
                                  .SetSerialNumber(BigInteger.One)
                                  .SetSubject(new X500Principal($"CN={ProtectedDataKey} CA Certificate"))
                                  .SetStartDate(calendar.Time)
                                  .SetEndDate(endDate.Time)
                                  .SetKeySize(2048);

                    keyGenerator.Initialize(builder.Build());
                }
                else
                {
                    var builder = new KeyGenParameterSpec.Builder(ProtectedDataKey, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                                  .SetBlockModes(KeyProperties.BlockModeEcb)
                                  .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                                  .SetRandomizedEncryptionRequired(false)
                                  .SetKeySize(2048);

                    keyGenerator.Initialize(builder.Build());
                }

                keyGenerator.GenerateKeyPair();
            }
        }
示例#13
0
        private KeyPair GenerateKeyPair(string keyName, bool invalidatedByBiometricEnrollment)
        {
            var keyPairGenerator = KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmEc, KEY_STORE_NAME);
            var builder          = new KeyGenParameterSpec.Builder(keyName, KeyStorePurpose.Sign)
                                   .SetAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
                                   .SetDigests(KeyProperties.DigestSha256, KeyProperties.DigestSha384, KeyProperties.DigestSha512)
                                   // Require the user to authenticate with a biometric to authorize every use of the key
                                   .SetUserAuthenticationRequired(true)
                                   // Generated keys will be invalidated if the biometric templates are added more to user device
                                   .SetInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);

            keyPairGenerator.Initialize(builder.Build());

            return(keyPairGenerator.GenerateKeyPair());
        }
示例#14
0
        /// <summary>
        /// To be added.
        /// </summary>
        /// <returns></returns>
        public static Javax.Crypto.ISecretKey GenerateKey(string keyStoreAlias)
        {
            var keyStore     = Java.Security.KeyStore.GetInstance("AndroidKeyStore");
            var keyGenerator = Javax.Crypto.KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore");

            keyStore.Load(null);

            var keyParameterSpec = new KeyGenParameterSpec.Builder(keyStoreAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                                   .SetBlockModes(KeyProperties.BlockModeCbc)
                                   .SetUserAuthenticationRequired(true)
                                   .SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7)
                                   .Build();

            keyGenerator.Init(keyParameterSpec);
            return(keyGenerator.GenerateKey());
        }
        private static void InitializePrivateKey()
        {
            var keyStore = KeyStore.GetInstance("AndroidKeyStore");

            keyStore.Load(null);
            var entry = keyStore.GetEntry(Alias, null);

            if (entry != null && entry is KeyStore.SecretKeyEntry)
            {
                return;
            }

            var keyBuilder = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore");
            var spec       = new KeyGenParameterSpec.Builder(Alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt).SetBlockModes(KeyProperties.BlockModeCbc).SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7).Build();

            keyBuilder.Init(spec);
            keyBuilder.GenerateKey();
        }
        //API 23+ Only
        public ISecretKey GetSymmetricKey()
        {
            var existingkey = keyStore.GetKey(alias, null);

            if (existingkey != null)
            {
                var existingSecretKey = existingkey.JavaCast <ISecretKey>();
                return(existingSecretKey);
            }
            var keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, CONST_ANDROIDKEY);
            var builder      = new KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                               .SetBlockModes(KeyProperties.BlockModeGcm)
                               .SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone)
                               .SetRandomizedEncryptionRequired(false);

            keyGenerator.Init(builder.Build());
            return(keyGenerator.GenerateKey());
        }
示例#17
0
        /// <summary>
        /// Creates a symmetric key in the Android Key Store which can only be used after the user
        /// has authenticated with biometry.
        /// </summary>
        private void CreateKey()
        {
            try
            {
                _keystore.Load(null);
                KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(GetAlias(_keyId),
                                                                                      KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                                                      .SetBlockModes(KeyProperties.BlockModeCbc)
                                                      // Require the user to authenticate with biometry to authorize every use
                                                      // of the key
                                                      .SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7)
                                                      .SetUserAuthenticationRequired(true);

                if ((int)Build.VERSION.SdkInt >= 24)
                {
                    builder.SetInvalidatedByBiometricEnrollment(true);
                }

                _keyGen.Init(
                    builder
                    .Build());
                _keyGen.GenerateKey();
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new RuntimeException(e);
            }
            catch (InvalidAlgorithmParameterException e)
            {
                throw new RuntimeException(e);
            }
            catch (CertificateException e)
            {
                throw new RuntimeException(e);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            catch (System.Exception e)
            {
                Kp2aLog.LogUnexpectedError(e);
            }
        }
示例#18
0
        /// <summary>
        /// Creates a new public-private key pair. An already existing key will be deleted, so
        /// make sure to call <see cref="KeysExistInKeyStore"/> before.
        /// </summary>
        private void CreateKeyPairInKeyStore()
        {
            RemoveKeyFromKeyStore();
            KeyPairGenerator keyGenerator =
                KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KeyStoreName);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2 &&
                Build.VERSION.SdkInt <= BuildVersionCodes.LollipopMr1)
            {
                Calendar startDateCalendar = Calendar.GetInstance(Locale.Default);
                startDateCalendar.Add(CalendarField.Year, -1);
                Calendar endDateCalendar = Calendar.GetInstance(Locale.Default);
                endDateCalendar.Add(CalendarField.Year, 100);
                string certificateName = string.Format("CN={0} CA Certificate", KeyAlias);

                // this API is obsolete after Android M, but we are supporting Android L
#pragma warning disable 618
                var builder = new KeyPairGeneratorSpec.Builder(_applicationContext)
                              .SetAlias(KeyAlias)
                              .SetSerialNumber(BigInteger.One)
                              .SetSubject(new X500Principal(certificateName))
                              .SetStartDate(startDateCalendar.Time)
                              .SetEndDate(endDateCalendar.Time)
                              .SetKeySize(KeySize);
#pragma warning restore 618

                keyGenerator.Initialize(builder.Build());
            }
            else if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                Calendar endDateCalendar = Calendar.GetInstance(Locale.Default);
                endDateCalendar.Add(CalendarField.Year, 100);

                var builder = new KeyGenParameterSpec.Builder(KeyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                              .SetBlockModes(KeyProperties.BlockModeEcb)
                              .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                              .SetCertificateNotAfter(endDateCalendar.Time)
                              .SetKeySize(KeySize);
                keyGenerator.Initialize(builder.Build());
            }

            // Key generator is initialized, generate the key
            keyGenerator.GenerateKeyPair();
        }
示例#19
0
 private void CreateKey()
 {
     try
     {
         var keyGen     = KeyGenerator.GetInstance(KeyAlgorithm, KeyStoreName);
         var keyGenSpec =
             new KeyGenParameterSpec.Builder(KeyName, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
             .SetBlockModes(BlockMode)
             .SetEncryptionPaddings(EncryptionPadding)
             .SetUserAuthenticationRequired(true)
             .Build();
         keyGen.Init(keyGenSpec);
         keyGen.GenerateKey();
     }
     catch
     {
         // Catch silently to allow biometrics to function on devices that are in a state where key generation
         // is not functioning
     }
 }
示例#20
0
        public void CreateKey()
        {
            // Removes key if it already exists, no change otherwise
            DeleteKey();
            KeyPairGenerator keyGenerator =
                KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME);

            // Parameters affiliated with the Transformation settings used when making Cipher
            var builder = new KeyGenParameterSpec.Builder(_keyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                          .SetBlockModes(KeyProperties.BlockModeEcb)
                          .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                          .SetRandomizedEncryptionRequired(false).SetKeySize(KEY_SIZE);

            keyGenerator.Initialize(builder.Build());
            builder.Dispose();

            // Keys automattically added to KeyStore
            keyGenerator.GenerateKeyPair();
            keyGenerator.Dispose();
        }
示例#21
0
        // API 23+ Only
        ISecretKey GetSymmetricKey()
        {
            Preferences.Set(useSymmetricPreferenceKey, true, SecureStorage.Alias);

            var existingKey = keyStore.GetKey(alias, null);

            if (existingKey != null)
            {
                var existingSecretKey = existingKey.JavaCast <ISecretKey>();
                return(existingSecretKey);
            }

            var keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, androidKeyStore);
            var builder      = new KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                               .SetBlockModes(KeyProperties.BlockModeGcm)
                               .SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone)
                               .SetRandomizedEncryptionRequired(false);

            keyGenerator.Init(builder.Build());

            return(keyGenerator.GenerateKey());
        }
        /// <summary>
        /// Creates a new public-private key pair. An already existing key will be deleted, so
        /// make sure to call <see cref="KeysExistInKeyStore"/> before.
        /// </summary>
        private void CreateKeyPairInKeyStore()
        {
            RemoveKeyFromKeyStore();
            KeyPairGenerator keyGenerator =
                KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KeyStoreName);

            // With Build.VERSION.SdkInt < BuildVersionCodes.M we would have to use an alternative
            // way, but Android 6 is our min version.
            Calendar endDateCalendar = Calendar.GetInstance(Locale.Default);

            endDateCalendar.Add(CalendarField.Year, 100);

            var builder = new KeyGenParameterSpec.Builder(KeyAlias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                          .SetBlockModes(KeyProperties.BlockModeEcb)
                          .SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
                          .SetCertificateNotAfter(endDateCalendar.Time)
                          .SetKeySize(KeySize);

            keyGenerator.Initialize(builder.Build());

            // Key generator is initialized, generate the key
            keyGenerator.GenerateKeyPair();
        }
示例#23
0
            private void CreateKey_Credentials()
            {
                var generator = KeyPairGenerator.GetInstance("RSA", AndroidKeyStore);

                if (Build.VERSION.SdkInt < BuildVersionCodes.M)
                {
                    Java.Util.Calendar calendar = Java.Util.Calendar.Instance;
                    calendar.Add(Java.Util.CalendarField.Year, 20);

                    Date startDate = Java.Util.Calendar.Instance.Time;
                    Date endDate   = calendar.Time;

#pragma warning disable 0618

                    var builder = new KeyPairGeneratorSpec.Builder(_context);

#pragma warning restore 0618

                    builder.SetAlias(KEYALIAS_CREDENTIALS);
                    builder.SetSerialNumber(Java.Math.BigInteger.One);
                    builder.SetSubject(new Javax.Security.Auth.X500.X500Principal("CN=${alias} CA Certificate"));
                    builder.SetStartDate(startDate);
                    builder.SetEndDate(endDate);

                    generator.Initialize(builder.Build());
                }
                else
                {
                    var builder = new KeyGenParameterSpec.Builder(KEYALIAS_CREDENTIALS, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt);
                    builder.SetBlockModes(KeyProperties.BlockModeEcb);
                    builder.SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1);
                    generator.Initialize(builder.Build());
                }

                generator.GenerateKeyPair();
            }
        private static void InitializePrivateKey()
        {
            var keyStore = KeyStore.GetInstance("AndroidKeyStore");
            keyStore.Load(null);
            var entry = keyStore.GetEntry(Alias, null);
            if(entry != null && entry is KeyStore.SecretKeyEntry) {
                return;
            }

            var keyBuilder = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore");
            var spec = new KeyGenParameterSpec.Builder(Alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt).SetBlockModes(KeyProperties.BlockModeCbc).SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7).Build();
            keyBuilder.Init(spec);
            keyBuilder.GenerateKey();
        }
 /// <summary>
 ///     Creates the Key for fingerprint authentication.
 /// </summary>
 void CreateKey()
 {
     KeyGenerator keyGen = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, KEYSTORE_NAME);
     KeyGenParameterSpec keyGenSpec =
         new KeyGenParameterSpec.Builder(KEY_NAME, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
             .SetBlockModes(BLOCK_MODE)
             .SetEncryptionPaddings(ENCRYPTION_PADDING)
             .SetUserAuthenticationRequired(true)
             .Build();
     keyGen.Init(keyGenSpec);
     keyGen.GenerateKey();
     Log.Debug(TAG, "New key created for fingerprint authentication.");
 }