Example #1
0
 private string AesEncrypt(byte[] input)
 {
     using (var entry = _keyStore.GetKey(KeyAlias, null))
         using (var cipher = Cipher.GetInstance(AesMode))
         {
             cipher.Init(CipherMode.EncryptMode, entry);
             var encBytes = cipher.DoFinal(input);
             var ivBytes  = cipher.GetIV();
             return($"{Convert.ToBase64String(ivBytes)}|{Convert.ToBase64String(encBytes)}");
         }
 }
        public Task <bool> ValidateIntegrityAsync()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.M)
            {
                return(Task.FromResult(true));
            }

            _keystore.Load(null);
            IKey   key    = _keystore.GetKey(KeyName, null);
            Cipher cipher = Cipher.GetInstance(Transformation);

            try
            {
                cipher.Init(CipherMode.EncryptMode, key);
            }
            catch (KeyPermanentlyInvalidatedException e)
            {
                // Biometric has changed
                return(Task.FromResult(false));
            }
            catch (UnrecoverableKeyException e)
            {
                // Biometric was disabled and re-enabled
                return(Task.FromResult(false));
            }
            catch (InvalidKeyException e)
            {
                // Fallback for old bitwarden users without a key
                CreateKey();
            }

            return(Task.FromResult(true));
        }
Example #3
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());
        }
Example #4
0
 void InitCipher()
 {
     try {
         mKeyStore.Load(null);
         var key = mKeyStore.GetKey(KEY_NAME, null);
         mCipher.Init(CipherMode.EncryptMode, key);
     } catch (KeyPermanentlyInvalidatedException e) {
         // This happens if the lock screen has been disabled or reset after the key was
         // generated, or if a fingerprint got enrolled after the key was generated.
         Toast.MakeText(this, "Keys are invalidated after created. Retry the purchase\n"
                        + e.Message, ToastLength.Long).Show();
     } catch (KeyStoreException e) {
         throw new RuntimeException("Failed to init Cipher", e);
     } catch (CertificateException e) {
         throw new RuntimeException("Failed to init Cipher", e);
     } catch (UnrecoverableKeyException e) {
         throw new RuntimeException("Failed to init Cipher", e);
     } catch (IOException e) {
         throw new RuntimeException("Failed to init Cipher", e);
     } catch (NoSuchAlgorithmException e) {
         throw new RuntimeException("Failed to init Cipher", e);
     } catch (InvalidKeyException e) {
         throw new RuntimeException("Failed to init Cipher", e);
     }
 }
Example #5
0
        private BiometricPrompt.CryptoObject BuildSymmetricCryptoObject(string keyName, string cipherName, CipherMode mode, byte[] iv = null)
        {
            if (this.Log().IsEnabled(LogLevel.Debug))
            {
                this.Log().Debug($"Building a symmetric crypto object (key name: '{keyName}', mode: '{mode}').");
            }

            var cipher = Cipher.GetInstance(cipherName);

            if (_keyStore.IsKeyEntry(keyName))
            {
                if (mode == CipherMode.EncryptMode)
                {
                    _keyStore.DeleteEntry(keyName);
                }
                else if (mode == CipherMode.DecryptMode)
                {
                    try
                    {
                        cipher.Init(mode, _keyStore.GetKey(keyName, null), new IvParameterSpec(iv));

                        return(new BiometricPrompt.CryptoObject(cipher));
                    }
                    catch (KeyPermanentlyInvalidatedException)
                    {
                        _keyStore.DeleteEntry(keyName);

                        throw;
                    }
                }
            }
            else if (mode == CipherMode.DecryptMode)
            {
                throw new ArgumentException("Key not found.");
            }

            GenerateSymmetricKey(keyName);

            cipher.Init(mode, _keyStore.GetKey(keyName, null));

            if (this.Log().IsEnabled(LogLevel.Information))
            {
                this.Log().Info($"Return the symmetric crypto object (key name: '{keyName}', mode: '{mode}').");
            }

            return(new BiometricPrompt.CryptoObject(cipher));
        }
Example #6
0
 private IKey GetPrivateKey()
 {
     if (!_androidKeyStore.ContainsAlias(_keyAlias))
     {
         return(null);
     }
     return(_androidKeyStore.GetKey(_keyAlias, null));
 }
Example #7
0
 public IKey GetPrivateKey()
 {
     if (!_androidKeyStore.ContainsAlias(_keyName))
     {
         return(null);
     }
     return(_androidKeyStore.GetKey(_keyName, null));
 }
        //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());
        }
        /// <summary>
        ///     Will get the key from the Android keystore, creating it if necessary.
        /// </summary>
        /// <returns></returns>
        IKey GetKey()
        {
            if (!_keystore.IsKeyEntry(_keyName))
            {
                CreateKey();
            }

            IKey secretKey = _keystore.GetKey(_keyName, null);

            return(secretKey);
        }
Example #10
0
        public string GetKey()
        {
            IKey secretKey;

            if (!_keystore.IsKeyEntry(KEY_NAME))
            {
                GenKey();
            }
            secretKey = _keystore.GetKey(KEY_NAME, null);
            return(secretKey.ToString());
        }
Example #11
0
        /// <summary>
        ///     Will get the key from the Android keystore, creating it if necessary.
        /// </summary>
        /// <returns></returns>
        IKey GetKey()
        {
            if (!_keystore.IsKeyEntry(KEY_NAME))
            {
                CreateKey();
            }

            IKey secretKey = _keystore.GetKey(KEY_NAME, null);

            return(secretKey);
        }
Example #12
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());
        }
Example #13
0
        /// <summary>
        /// Decrypts a value using the system wide key.
        ///
        /// Expects encrypted to be encoded in base64.
        ///
        /// If the byte version doesn't match the current key version,
        /// outOfDate will be set and the value should be re-encrypted and stored
        /// before completing any other operation.
        /// </summary>
        public static string Decrypt(string encrypted, string iv, byte version, string hmac, out bool outOfDate)
        {
            using (MiniProfiler.Current.Step("Decrypt"))
            {
                outOfDate = false;

                var encryptedBytes = Convert.FromBase64String(encrypted);
                var ivBytes        = Convert.FromBase64String(iv);

                // Value encrypted using an old key encountered
                if (version != AesKeyVersion)
                {
                    var oldKey = KeyStore.GetKey(version);

                    // Different crypto keys means different hmac keys, gotta spin up an old one
                    var oldHmac = new HMACSHA1();
                    oldHmac.Key = Convert.FromBase64String(oldKey.HMAC);

                    if (hmac != Convert.ToBase64String(oldHmac.ComputeHash(Convert.FromBase64String(encrypted))))
                    {
                        throw new Exception("HMAC validation failed on encrypted value (key version = " + oldKey.Version + ")");
                    }

                    ICryptoTransform oldDecryptor;

                    lock (AesProvider)
                        oldDecryptor = AesProvider.CreateDecryptor(Convert.FromBase64String(oldKey.Encryption), ivBytes);


                    var retBytes = oldDecryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);

                    outOfDate = true;
                    return(Encoding.UTF8.GetString(retBytes));
                }

                var shouldMatchHMAC = MakeAuthCode(Convert.FromBase64String(encrypted));

                if (hmac != shouldMatchHMAC)
                {
                    throw new Exception("HMAC validation failed on encrypted value");
                }

                ICryptoTransform decryptor;
                lock (AesProvider)
                    decryptor = AesProvider.CreateDecryptor(AesKey, ivBytes);

                var ret = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);

                return(Encoding.UTF8.GetString(ret));
            }
        }
        public byte[] Sign(byte[] data)
        {
            ISigner sign = SignerUtilities.GetSigner("SHA256withRSA");

            // Yes! Encrypt data with Private key becase this is "digital signing!!"
            // Asymmetric Encryption : encrypt with public key and decrypt with private key.
            // Digital Signing : encrypt with private key and decrypt with public key.
            ICipherParameters privateKey = KeyStore.GetKey(Alias).Key;

            sign.Init(true, privateKey);
            sign.BlockUpdate(data, 0, data.Length);
            byte[] signature = sign.GenerateSignature();
            return(signature);
        }
        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();
            }
        }
Example #16
0
 private bool CipherInit()
 {
     try
     {
         cipher = Cipher.GetInstance(KeyProperties.KeyAlgorithmAes + "/" + KeyProperties.BlockModeCbc + "/" + KeyProperties.EncryptionPaddingPkcs7);
         keyStore.Load(null);
         IKey key = (IKey)keyStore.GetKey(KEY_NAME, null);
         cipher.Init(CipherMode.EncryptMode, key);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #17
0
 private bool _genereazaCifru()
 {
     try
     {
         _cifru = Cipher.GetInstance(_transforma);
         _creareCheie.Load(null);
         IKey _ch = _creareCheie.GetKey(_cheie, null);
         _cifru.Init(CipherMode.EncryptMode, _ch);
         return(true);
     }
     catch (Exception)
     {
         Toast.MakeText(this, "Can't generate encryption key for you", ToastLength.Short).Show();
         return(false);
     }
 }
Example #18
0
            //###############################################################################

            public SecureEncryptor(Context context)
            {
                _context = context;

                storeObject = KeyStore.GetInstance(AndroidKeyStore);
                storeObject.Load(null);


                if (!storeObject.ContainsAlias(KEYALIAS_CREDENTIALS))
                {
                    CreateKey_Credentials();
                }

                Key_private = storeObject.GetKey(KEYALIAS_CREDENTIALS, null);
                Key_public  = storeObject.GetCertificate(KEYALIAS_CREDENTIALS)?.PublicKey;
            }
Example #19
0
        public ActionResult Ping()
        {
            var dbCheck = Current.ReadDB.Users.FirstOrDefault();

            Current.AddToCache("ping-sanity-check", "dummy-value", TimeSpan.FromMinutes(1));
            var cache = Current.GetFromCache <string>("string-not-found") ?? "";

            KeyStore.GetKey(KeyStore.LatestKeyVersion);

            return
                (new ContentResult
            {
                Content = Environment.MachineName + cache,
                ContentType = "text/plain",
                ContentEncoding = Encoding.UTF8
            });
        }
 private void InitCipher(Cipher cipher, string storeKeyName)
 {
     try
     {
         keyStore.Load(null);
         IKey secretKey = keyStore.GetKey(storeKeyName, null);
         cipher.Init(CipherMode.EncryptMode, secretKey);
     }
     catch (Java.Lang.Exception e)
     {
         if (e is KeyStoreException | e is CertificateException | e is UnrecoverableKeyException | e is IOException
             | e is NoSuchAlgorithmException | e is InvalidKeyException)
         {
             throw new RuntimeException("Failed to init Cipher. " + e.Message, e);
         }
     }
 }
 private bool CipherInit()
 {
     try
     {
         cipher = Cipher.GetInstance(KeyProperties.KeyAlgorithmAes + "/" +
                                     KeyProperties.BlockModeCbc + "/" +
                                     KeyProperties.EncryptionPaddingPkcs7);
         keyStore.Load(null);
         IKey key = (IKey)keyStore.GetKey(KEY_NAME, null);
         cipher.Init(CipherMode.EncryptMode, key);
         return(true);
     }
     catch (Exception ex)
     {
         Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
         return(false);
     }
 }
 /// <exception cref="System.IO.IOException"/>
 public override CredentialProvider.CredentialEntry GetCredentialEntry(string alias
                                                                       )
 {
     readLock.Lock();
     try
     {
         SecretKeySpec key = null;
         try
         {
             if (cache.Contains(alias))
             {
                 return(cache[alias]);
             }
             if (!keyStore.ContainsAlias(alias))
             {
                 return(null);
             }
             key = (SecretKeySpec)keyStore.GetKey(alias, password);
         }
         catch (KeyStoreException e)
         {
             throw new IOException("Can't get credential " + alias + " from " + GetPathAsString
                                       (), e);
         }
         catch (NoSuchAlgorithmException e)
         {
             throw new IOException("Can't get algorithm for credential " + alias + " from " +
                                   GetPathAsString(), e);
         }
         catch (UnrecoverableKeyException e)
         {
             throw new IOException("Can't recover credential " + alias + " from " + GetPathAsString
                                       (), e);
         }
         return(new CredentialProvider.CredentialEntry(alias, BytesToChars(key.GetEncoded(
                                                                               ))));
     }
     finally
     {
         readLock.Unlock();
     }
 }
Example #23
0
        public Task <bool> ValidateIntegrityAsync(string bioIntegrityKey = null)
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.M)
            {
                return(Task.FromResult(true));
            }

            try
            {
                _keystore.Load(null);
                var key    = _keystore.GetKey(KeyName, null);
                var cipher = Cipher.GetInstance(Transformation);

                if (key == null || cipher == null)
                {
                    return(Task.FromResult(true));
                }

                cipher.Init(CipherMode.EncryptMode, key);
            }
            catch (KeyPermanentlyInvalidatedException e)
            {
                // Biometric has changed
                return(Task.FromResult(false));
            }
            catch (UnrecoverableKeyException e)
            {
                // Biometric was disabled and re-enabled
                return(Task.FromResult(false));
            }
            catch (InvalidKeyException e)
            {
                // Fallback for old bitwarden users without a key
#if !FDROID
                Crashes.TrackError(e);
#endif
                CreateKey();
            }

            return(Task.FromResult(true));
        }
        public override byte[] Decrypt(byte[] encryptedBytes, byte[] iv, string keyName = null)
        {
            var key = KeyStore.GetKey(keyName ?? PublicKeyName);

            using (var aes = Aes.Create())
            {
                aes.Key  = Encoding.UTF8.GetBytes(key);
                aes.IV   = iv;
                aes.Mode = CipherMode.CBC;

                var decrypter = aes.CreateDecryptor(aes.Key, aes.IV);
                using (var ms = new MemoryStream(encryptedBytes))
                {
                    using (var cs = new CryptoStream(ms, decrypter, CryptoStreamMode.Read))
                        using (var sr = new StreamReader(cs))
                        {
                            var value = sr.ReadToEnd();
                            return(System.Text.Encoding.UTF8.GetBytes(value));
                        }
                }
            }
        }
 public bool InitCipher()
 {
     try
     {
         mKeyStore.Load(null);
         var key = mKeyStore.GetKey(KEY_NAME, null);
         mCipher.Init(CipherMode.EncryptMode, key);
         return(true);
     }
     catch (KeyPermanentlyInvalidatedException)
     {
         return(false);
     }
     catch (KeyStoreException e)
     {
         throw new RuntimeException("Failed to init Cipher", e);
     }
     catch (CertificateException e)
     {
         throw new RuntimeException("Failed to init Cipher", e);
     }
     catch (UnrecoverableKeyException e)
     {
         throw new RuntimeException("Failed to init Cipher", e);
     }
     catch (IOException e)
     {
         throw new RuntimeException("Failed to init Cipher", e);
     }
     catch (NoSuchAlgorithmException e)
     {
         throw new RuntimeException("Failed to init Cipher", e);
     }
     catch (InvalidKeyException e)
     {
         throw new RuntimeException("Failed to init Cipher", e);
     }
 }
        public override byte[] Encrypt(byte[] plainBytes, out byte[] iv)
        {
            var key = KeyStore.GetKey(PublicKeyName);

            using (var aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.GenerateIV();
                iv = aes.IV;

                aes.Mode = CipherMode.CBC;
                var encrypter = aes.CreateEncryptor(aes.Key, aes.IV);

                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, encrypter, CryptoStreamMode.Write))
                    {
                        cs.Write(plainBytes, 0, plainBytes.Length);
                    }
                    return(ms.ToArray());
                }
            }
        }
        private AuthenticationParameters GetAuthenticationParameters(
            PowerShellTokenCacheProvider tokenCacheProvider,
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenant,
            SecureString password,
            string promptBehavior,
            Action <string> promptAction,
            IAzureTokenCache tokenCache,
            string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            switch (account.Type)
            {
            case AzureAccount.AccountType.User:
                if (password == null)
                {
                    var homeAccountId = account.GetProperty(AzureAccount.Property.HomeAccountId) ?? "";

                    if (!string.IsNullOrEmpty(account.Id))
                    {
                        return(new SilentParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId));
                    }

                    if (account.IsPropertySet("UseDeviceAuth"))
                    {
                        return(new DeviceCodeParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId));
                    }
                    else if (account.IsPropertySet(AzureAccount.Property.UsePasswordAuth))
                    {
                        return(new UsernamePasswordParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password, homeAccountId));
                    }
                    return(new InteractiveParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.GetProperty("LoginHint"), homeAccountId, promptAction));
                }

                return(new UsernamePasswordParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password, null));

            case AzureAccount.AccountType.Certificate:
            case AzureAccount.AccountType.ServicePrincipal:
                bool?sendCertificateChain    = null;
                var  sendCertificateChainStr = account.GetProperty(AzureAccount.Property.SendCertificateChain);
                if (!string.IsNullOrWhiteSpace(sendCertificateChainStr))
                {
                    sendCertificateChain = Boolean.Parse(sendCertificateChainStr);
                }
                password = password ?? account.GetProperty(AzureAccount.Property.ServicePrincipalSecret)?.ConvertToSecureString();
                if (password == null)
                {
                    password = KeyStore.GetKey(new ServicePrincipalKey(AzureAccount.Property.ServicePrincipalSecret
                                                                       , account.Id, tenant));
                }
                var certificatePassword = account.GetProperty(AzureAccount.Property.CertificatePassword)?.ConvertToSecureString();
                if (certificatePassword == null)
                {
                    certificatePassword = KeyStore.GetKey(new ServicePrincipalKey(AzureAccount.Property.CertificatePassword
                                                                                  , account.Id, tenant));
                }
                return(new ServicePrincipalParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, account.GetProperty(AzureAccount.Property.CertificateThumbprint), account.GetProperty(AzureAccount.Property.CertificatePath),
                                                      certificatePassword, password, sendCertificateChain));

            case AzureAccount.AccountType.ManagedService:
                return(new ManagedServiceIdentityParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account));

            case AzureAccount.AccountType.AccessToken:
                return(new AccessTokenParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account));

            case "ClientAssertion":
                password = password ?? account.GetProperty("ClientAssertion")?.ConvertToSecureString();
                return(new ClientAssertionParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password));

            default:
                return(null);
            }
        }