Search in sources :

Example 16 with KeyStore

use of android.security.KeyStore in project XobotOS by xamarin.

the class LockPatternUtils method saveLockPassword.

/**
     * Save a lock password.  Does not ensure that the password is as good
     * as the requested mode, but will adjust the mode to be as good as the
     * pattern.
     * @param password The password to save
     * @param quality {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)}
     * @param isFallback Specifies if this is a fallback to biometric weak
     */
public void saveLockPassword(String password, int quality, boolean isFallback) {
    // Compute the hash
    final byte[] hash = passwordToHash(password);
    try {
        // Write the hash to file
        RandomAccessFile raf = new RandomAccessFile(sLockPasswordFilename, "rw");
        // Truncate the file if pattern is null, to clear the lock
        if (password == null) {
            raf.setLength(0);
        } else {
            raf.write(hash, 0, hash.length);
        }
        raf.close();
        DevicePolicyManager dpm = getDevicePolicyManager();
        KeyStore keyStore = KeyStore.getInstance();
        if (password != null) {
            // Update the encryption password.
            updateEncryptionPassword(password);
            // Update the keystore password
            keyStore.password(password);
            int computedQuality = computePasswordQuality(password);
            if (!isFallback) {
                deleteGallery();
                setLong(PASSWORD_TYPE_KEY, Math.max(quality, computedQuality));
            } else {
                setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK);
                setLong(PASSWORD_TYPE_ALTERNATE_KEY, Math.max(quality, computedQuality));
                setBoolean(BIOMETRIC_WEAK_EVER_CHOSEN_KEY, true);
                moveTempGallery();
            }
            if (computedQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
                int letters = 0;
                int uppercase = 0;
                int lowercase = 0;
                int numbers = 0;
                int symbols = 0;
                int nonletter = 0;
                for (int i = 0; i < password.length(); i++) {
                    char c = password.charAt(i);
                    if (c >= 'A' && c <= 'Z') {
                        letters++;
                        uppercase++;
                    } else if (c >= 'a' && c <= 'z') {
                        letters++;
                        lowercase++;
                    } else if (c >= '0' && c <= '9') {
                        numbers++;
                        nonletter++;
                    } else {
                        symbols++;
                        nonletter++;
                    }
                }
                dpm.setActivePasswordState(Math.max(quality, computedQuality), password.length(), letters, uppercase, lowercase, numbers, symbols, nonletter);
            } else {
                // The password is not anything.
                dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 0, 0, 0, 0, 0);
            }
            // Add the password to the password history. We assume all
            // password
            // hashes have the same length for simplicity of implementation.
            String passwordHistory = getString(PASSWORD_HISTORY_KEY);
            if (passwordHistory == null) {
                passwordHistory = new String();
            }
            int passwordHistoryLength = getRequestedPasswordHistoryLength();
            if (passwordHistoryLength == 0) {
                passwordHistory = "";
            } else {
                passwordHistory = new String(hash) + "," + passwordHistory;
                // Cut it to contain passwordHistoryLength hashes
                // and passwordHistoryLength -1 commas.
                passwordHistory = passwordHistory.substring(0, Math.min(hash.length * passwordHistoryLength + passwordHistoryLength - 1, passwordHistory.length()));
            }
            setString(PASSWORD_HISTORY_KEY, passwordHistory);
        } else {
            // non-empty, we are just switching key guard type
            if (keyStore.isEmpty()) {
                keyStore.reset();
            }
            dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 0, 0, 0, 0, 0);
        }
    } catch (FileNotFoundException fnfe) {
        // Cant do much, unless we want to fail over to using the settings provider
        Log.e(TAG, "Unable to save lock pattern to " + sLockPasswordFilename);
    } catch (IOException ioe) {
        // Cant do much
        Log.e(TAG, "Unable to save lock pattern to " + sLockPasswordFilename);
    }
}
Also used : DevicePolicyManager(android.app.admin.DevicePolicyManager) RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) KeyStore(android.security.KeyStore)

Example 17 with KeyStore

use of android.security.KeyStore in project XobotOS by xamarin.

the class LockPatternUtils method saveLockPattern.

/**
     * Save a lock pattern.
     * @param pattern The new pattern to save.
     * @param isFallback Specifies if this is a fallback to biometric weak
     */
public void saveLockPattern(List<LockPatternView.Cell> pattern, boolean isFallback) {
    // Compute the hash
    final byte[] hash = LockPatternUtils.patternToHash(pattern);
    try {
        // Write the hash to file
        RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "rw");
        // Truncate the file if pattern is null, to clear the lock
        if (pattern == null) {
            raf.setLength(0);
        } else {
            raf.write(hash, 0, hash.length);
        }
        raf.close();
        DevicePolicyManager dpm = getDevicePolicyManager();
        KeyStore keyStore = KeyStore.getInstance();
        if (pattern != null) {
            keyStore.password(patternToString(pattern));
            setBoolean(PATTERN_EVER_CHOSEN_KEY, true);
            if (!isFallback) {
                deleteGallery();
                setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
            } else {
                setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK);
                setLong(PASSWORD_TYPE_ALTERNATE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
                setBoolean(BIOMETRIC_WEAK_EVER_CHOSEN_KEY, true);
                moveTempGallery();
            }
            dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, pattern.size(), 0, 0, 0, 0, 0, 0);
        } else {
            if (keyStore.isEmpty()) {
                keyStore.reset();
            }
            dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 0, 0, 0, 0, 0);
        }
    } catch (FileNotFoundException fnfe) {
        // Cant do much, unless we want to fail over to using the settings
        // provider
        Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
    } catch (IOException ioe) {
        // Cant do much
        Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
    }
}
Also used : DevicePolicyManager(android.app.admin.DevicePolicyManager) RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) KeyStore(android.security.KeyStore)

Example 18 with KeyStore

use of android.security.KeyStore in project android_frameworks_base by DirtyUnicorns.

the class LockSettingsService method removeUser.

private void removeUser(int userId, boolean unknownUser) {
    mStorage.removeUser(userId);
    mStrongAuth.removeUser(userId);
    final KeyStore ks = KeyStore.getInstance();
    ks.onUserRemoved(userId);
    try {
        final IGateKeeperService gk = getGateKeeperService();
        if (gk != null) {
            gk.clearSecureUserId(userId);
        }
    } catch (RemoteException ex) {
        Slog.w(TAG, "unable to clear GK secure user id");
    }
    if (unknownUser || mUserManager.getUserInfo(userId).isManagedProfile()) {
        removeKeystoreProfileKey(userId);
    }
}
Also used : IGateKeeperService(android.service.gatekeeper.IGateKeeperService) RemoteException(android.os.RemoteException) KeyStore(android.security.KeyStore)

Example 19 with KeyStore

use of android.security.KeyStore in project android_frameworks_base by DirtyUnicorns.

the class LockSettingsService method tieProfileLockToParent.

private void tieProfileLockToParent(int userId, String password) {
    if (DEBUG)
        Slog.v(TAG, "tieProfileLockToParent for user: " + userId);
    byte[] randomLockSeed = password.getBytes(StandardCharsets.UTF_8);
    byte[] encryptionResult;
    byte[] iv;
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
        keyGenerator.init(new SecureRandom());
        SecretKey secretKey = keyGenerator.generateKey();
        java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        try {
            keyStore.setEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, new java.security.KeyStore.SecretKeyEntry(secretKey), new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build());
            keyStore.setEntry(LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId, new java.security.KeyStore.SecretKeyEntry(secretKey), new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).setUserAuthenticationRequired(true).setUserAuthenticationValidityDurationSeconds(30).build());
            // Key imported, obtain a reference to it.
            SecretKey keyStoreEncryptionKey = (SecretKey) keyStore.getKey(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, null);
            Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE);
            cipher.init(Cipher.ENCRYPT_MODE, keyStoreEncryptionKey);
            encryptionResult = cipher.doFinal(randomLockSeed);
            iv = cipher.getIV();
        } finally {
            // The original key can now be discarded.
            keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId);
        }
    } catch (CertificateException | UnrecoverableKeyException | IOException | BadPaddingException | IllegalBlockSizeException | KeyStoreException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
        throw new RuntimeException("Failed to encrypt key", e);
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        if (iv.length != PROFILE_KEY_IV_SIZE) {
            throw new RuntimeException("Invalid iv length: " + iv.length);
        }
        outputStream.write(iv);
        outputStream.write(encryptionResult);
    } catch (IOException e) {
        throw new RuntimeException("Failed to concatenate byte arrays", e);
    }
    mStorage.writeChildProfileLock(userId, outputStream.toByteArray());
}
Also used : SecureRandom(java.security.SecureRandom) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvalidKeyException(java.security.InvalidKeyException) KeyStore(android.security.KeyStore) SecretKey(javax.crypto.SecretKey) UnrecoverableKeyException(java.security.UnrecoverableKeyException) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator)

Example 20 with KeyStore

use of android.security.KeyStore in project android_frameworks_base by DirtyUnicorns.

the class LockSettingsService method setKeystorePassword.

private void setKeystorePassword(String password, int userHandle) {
    final KeyStore ks = KeyStore.getInstance();
    ks.onUserPasswordChanged(userHandle, password);
}
Also used : KeyStore(android.security.KeyStore)

Aggregations

KeyStore (android.security.KeyStore)26 RemoteException (android.os.RemoteException)8 IOException (java.io.IOException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 CertificateException (java.security.cert.CertificateException)6 IGateKeeperService (android.service.gatekeeper.IGateKeeperService)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 InvalidKeyException (java.security.InvalidKeyException)5 KeyStoreException (java.security.KeyStoreException)5 SecureRandom (java.security.SecureRandom)5 UnrecoverableKeyException (java.security.UnrecoverableKeyException)5 BadPaddingException (javax.crypto.BadPaddingException)5 Cipher (javax.crypto.Cipher)5 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)5 KeyGenerator (javax.crypto.KeyGenerator)5 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)5 SecretKey (javax.crypto.SecretKey)5 DevicePolicyManager (android.app.admin.DevicePolicyManager)4 FileNotFoundException (java.io.FileNotFoundException)2 RandomAccessFile (java.io.RandomAccessFile)2