android.security.keystore.UserNotAuthenticatedException Java Examples

The following examples show how to use android.security.keystore.UserNotAuthenticatedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LockSettingsService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void unlockChildProfile(int profileHandle, boolean ignoreUserNotAuthenticated)
        throws RemoteException {
    try {
        doVerifyCredential(getDecryptedPasswordForTiedProfile(profileHandle),
                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
                false, 0 /* no challenge */, profileHandle, null /* progressCallback */);
    } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
            | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidAlgorithmParameterException | IllegalBlockSizeException
            | BadPaddingException | CertificateException | IOException e) {
        if (e instanceof FileNotFoundException) {
            Slog.i(TAG, "Child profile key not found");
        } else if (ignoreUserNotAuthenticated && e instanceof UserNotAuthenticatedException) {
            Slog.i(TAG, "Parent keystore seems locked, ignoring");
        } else {
            Slog.e(TAG, "Failed to decrypt child profile key", e);
        }
    }
}
 
Example #2
Source File: DecrypterManagerTest.java    From capillary with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthCiphertextsSavedWithNewScreenLock() throws Exception {
  // Emulate a newly added screen lock on a device with API level 23 or later.
  TestUtils.setBuildVersion(VERSION_CODES.M);
  when(hybridDecrypt.decrypt(any(byte[].class), any(byte[].class)))
      .thenThrow(new UserNotAuthenticatedException());

  ciphertextBuilder.setIsAuthKey(true);
  byte[] ciphertextBytes = ciphertextBuilder.build().toByteArray();

  decrypterManager.decrypt(ciphertextBytes, handler, extra);
  verify(handler).authCiphertextSavedForLater(ciphertextBytes, extra);
  verifyNoMoreInteractions(handler);
}
 
Example #3
Source File: BaseEncryptionManager.java    From samples-android with Apache License 2.0 5 votes vote down vote up
private void initDecodeCipher(String keyAlias, int mode) throws GeneralSecurityException {
    PrivateKey key = (PrivateKey) mKeyStore.getKey(keyAlias, null);
    try {
        mCipher.init(mode, key);
    } catch (InvalidKeyException e) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (e instanceof UserNotAuthenticatedException) {
                throw new OktaUserNotAuthenticateException(
                        getUserNotAuthenticatedMessage(mCipher), e);
            }
        }
        throw e;
    }
}
 
Example #4
Source File: BaseEncryptionManager.java    From samples-android with Apache License 2.0 5 votes vote down vote up
@Override
public String decrypt(String encryptedString) throws GeneralSecurityException {
    try {
        if (encryptedString != null && encryptedString.length() > 0) {
            if (mCipher == null) {
                throw new InvalidParameterException(
                        "Cipher is null. Please initialize proper cipher");
            }
            if (initCipher(mKeyAlias, Cipher.DECRYPT_MODE)) {
                StringBuilder decryptedBuilder = new StringBuilder();
                String[] chunks = encryptedString.split(CHUNK_SEPARATOR);
                for (String chunk : chunks) {
                    byte[] bytes = Base64.decode(chunk, Base64.NO_WRAP);
                    decryptedBuilder.append(new String(mCipher.doFinal(bytes)));
                }
                return decryptedBuilder.toString();
            }
        }
        return encryptedString;
    } catch (IllegalBlockSizeException e) {
        // We generate keys using UserAuthenticationValidityDurationSeconds parameter.
        // We decrypt data by chunk. This exception could be if this validity duration ended
        // during decryption. In this reason we check cause exception and provide valid
        // exception to user space
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && e.getCause() instanceof UserNotAuthenticatedException) {
            throw new OktaUserNotAuthenticateException(
                    getUserNotAuthenticatedMessage(mCipher), e);
        }
        throw e;
    }
}
 
Example #5
Source File: KeychainAuthenticatedActivity.java    From Android-Vault with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean handleRuntimeException(SharedPreferenceVault sharedPreferenceVault, int requestCode, Throwable throwable) {
    boolean handled = false;
    if (throwable instanceof UserNotAuthenticatedException) {
        Log.w(TAG, "User authentication expired");
        showAuthenticationScreen(requestCode);
        handled = true;
    } else if (throwable instanceof KeyPermanentlyInvalidatedException) {
        Log.w(TAG, "User changed unlock code and permanently invalidated the key");
        sharedPreferenceVault.rekeyStorage(null);
        completeOperationForRequestCode(requestCode);
        handled = true;
    }
    return handled;
}
 
Example #6
Source File: CipherStorageKeystoreRsaEcb.java    From react-native-keychain with MIT License 5 votes vote down vote up
@Override
@SuppressLint("NewApi")
public void decrypt(@NonNull DecryptionResultHandler handler,
                    @NonNull String alias,
                    @NonNull byte[] username,
                    @NonNull byte[] password,
                    @NonNull final SecurityLevel level)
  throws CryptoFailedException {

  throwIfInsufficientLevel(level);

  final String safeAlias = getDefaultAliasIfEmpty(alias, getDefaultAliasServiceName());
  final AtomicInteger retries = new AtomicInteger(1);
  boolean shouldAskPermissions = false;

  Key key = null;

  try {
    // key is always NOT NULL otherwise GeneralSecurityException raised
    key = extractGeneratedKey(safeAlias, level, retries);

    final DecryptionResult results = new DecryptionResult(
      decryptBytes(key, username),
      decryptBytes(key, password)
    );

    handler.onDecrypt(results, null);
  } catch (final UserNotAuthenticatedException ex) {
    Log.d(LOG_TAG, "Unlock of keystore is needed. Error: " + ex.getMessage(), ex);

    // expected that KEY instance is extracted and we caught exception on decryptBytes operation
    @SuppressWarnings("ConstantConditions") final DecryptionContext context =
      new DecryptionContext(safeAlias, key, password, username);

    handler.askAccessPermissions(context);
  } catch (final Throwable fail) {
    // any other exception treated as a failure
    handler.onDecrypt(null, fail);
  }
}