Search in sources :

Example 86 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project android_frameworks_base by ResurrectionRemix.

the class LockSettingsService method verifyTiedProfileChallenge.

@Override
public VerifyCredentialResponse verifyTiedProfileChallenge(String password, boolean isPattern, long challenge, int userId) throws RemoteException {
    checkPasswordReadPermission(userId);
    if (!isManagedProfileWithUnifiedLock(userId)) {
        throw new RemoteException("User id must be managed profile with unified lock");
    }
    final int parentProfileId = mUserManager.getProfileParent(userId).id;
    // Unlock parent by using parent's challenge
    final VerifyCredentialResponse parentResponse = isPattern ? doVerifyPattern(password, true, challenge, parentProfileId, null) : doVerifyPassword(password, true, challenge, parentProfileId, null);
    if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
        // Failed, just return parent's response
        return parentResponse;
    }
    try {
        // Unlock work profile, and work profile with unified lock must use password only
        return doVerifyPassword(getDecryptedPasswordForTiedProfile(userId), true, challenge, userId, null);
    } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
        Slog.e(TAG, "Failed to decrypt child profile key", e);
        throw new RemoteException("Unable to get tied profile token");
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) VerifyCredentialResponse(com.android.internal.widget.VerifyCredentialResponse) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RemoteException(android.os.RemoteException)

Example 87 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project android_frameworks_base by ResurrectionRemix.

the class LockSettingsService method resetKeyStore.

@Override
public void resetKeyStore(int userId) throws RemoteException {
    checkWritePermission(userId);
    if (DEBUG)
        Slog.v(TAG, "Reset keystore for user: " + userId);
    int managedUserId = -1;
    String managedUserDecryptedPassword = null;
    final List<UserInfo> profiles = mUserManager.getProfiles(userId);
    for (UserInfo pi : profiles) {
        // Unlock managed profile with unified lock
        if (pi.isManagedProfile() && !mLockPatternUtils.isSeparateProfileChallengeEnabled(pi.id) && mStorage.hasChildProfileLock(pi.id)) {
            try {
                if (managedUserId == -1) {
                    managedUserDecryptedPassword = getDecryptedPasswordForTiedProfile(pi.id);
                    managedUserId = pi.id;
                } else {
                    // Should not happen
                    Slog.e(TAG, "More than one managed profile, uid1:" + managedUserId + ", uid2:" + pi.id);
                }
            } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
                Slog.e(TAG, "Failed to decrypt child profile key", e);
            }
        }
    }
    try {
        // Clear all the users credentials could have been installed in for this user.
        for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
            for (int uid : SYSTEM_CREDENTIAL_UIDS) {
                mKeyStore.clearUid(UserHandle.getUid(profileId, uid));
            }
        }
    } finally {
        if (managedUserId != -1 && managedUserDecryptedPassword != null) {
            if (DEBUG)
                Slog.v(TAG, "Restore tied profile lock");
            tieProfileLockToParent(managedUserId, managedUserDecryptedPassword);
        }
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) UserInfo(android.content.pm.UserInfo) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) UnrecoverableKeyException(java.security.UnrecoverableKeyException)

Example 88 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project android_frameworks_base by ResurrectionRemix.

the class LockSettingsService method setLockPasswordInternal.

private void setLockPasswordInternal(String password, String savedCredential, int userId) throws RemoteException {
    byte[] currentHandle = getCurrentHandle(userId);
    if (password == null) {
        clearUserKeyProtection(userId);
        getGateKeeperService().clearSecureUserId(userId);
        mStorage.writePasswordHash(null, userId);
        setKeystorePassword(null, userId);
        fixateNewestUserKeyAuth(userId);
        onUserLockChanged(userId);
        notifyActivePasswordMetricsAvailable(null, userId);
        return;
    }
    if (isManagedProfileWithUnifiedLock(userId)) {
        // get credential from keystore when managed profile has unified lock
        try {
            savedCredential = getDecryptedPasswordForTiedProfile(userId);
        } catch (FileNotFoundException e) {
            Slog.i(TAG, "Child profile key not found");
        } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
            Slog.e(TAG, "Failed to decrypt child profile key", e);
        }
    } else {
        if (currentHandle == null) {
            if (savedCredential != null) {
                Slog.w(TAG, "Saved credential provided, but none stored");
            }
            savedCredential = null;
        }
    }
    byte[] enrolledHandle = enrollCredential(currentHandle, savedCredential, password, userId);
    if (enrolledHandle != null) {
        CredentialHash willStore = new CredentialHash(enrolledHandle, CredentialHash.VERSION_GATEKEEPER);
        setUserKeyProtection(userId, password, doVerifyPassword(password, willStore, true, 0, userId, null));
        mStorage.writePasswordHash(enrolledHandle, userId);
        fixateNewestUserKeyAuth(userId);
        onUserLockChanged(userId);
    } else {
        throw new RemoteException("Failed to enroll password");
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CredentialHash(com.android.server.LockSettingsStorage.CredentialHash) FileNotFoundException(java.io.FileNotFoundException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RemoteException(android.os.RemoteException)

Example 89 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project jdk8u_jdk by JetBrains.

the class PKCS12KeyStore method engineGetKey.

/**
     * Returns the key associated with the given alias, using the given
     * password to recover it.
     *
     * @param alias the alias name
     * @param password the password for recovering the key
     *
     * @return the requested key, or null if the given alias does not exist
     * or does not identify a <i>key entry</i>.
     *
     * @exception NoSuchAlgorithmException if the algorithm for recovering the
     * key cannot be found
     * @exception UnrecoverableKeyException if the key cannot be recovered
     * (e.g., the given password is wrong).
     */
public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException {
    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    Key key = null;
    if (entry == null || (!(entry instanceof KeyEntry))) {
        return null;
    }
    // get the encoded private key or secret key
    byte[] encrBytes = null;
    if (entry instanceof PrivateKeyEntry) {
        encrBytes = ((PrivateKeyEntry) entry).protectedPrivKey;
    } else if (entry instanceof SecretKeyEntry) {
        encrBytes = ((SecretKeyEntry) entry).protectedSecretKey;
    } else {
        throw new UnrecoverableKeyException("Error locating key");
    }
    byte[] encryptedKey;
    AlgorithmParameters algParams;
    ObjectIdentifier algOid;
    try {
        // get the encrypted private key
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
        encryptedKey = encrInfo.getEncryptedData();
        // parse Algorithm parameters
        DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
        DerInputStream in = val.toDerInputStream();
        algOid = in.getOID();
        algParams = parseAlgParameters(algOid, in);
    } catch (IOException ioe) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
        uke.initCause(ioe);
        throw uke;
    }
    try {
        byte[] keyInfo;
        while (true) {
            try {
                // Use JCE
                SecretKey skey = getPBEKey(password);
                Cipher cipher = Cipher.getInstance(mapPBEParamsToAlgorithm(algOid, algParams));
                cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
                keyInfo = cipher.doFinal(encryptedKey);
                break;
            } catch (Exception e) {
                if (password.length == 0) {
                    // Retry using an empty password
                    // without a NULL terminator.
                    password = new char[1];
                    continue;
                }
                throw e;
            }
        }
        /*
             * Parse the key algorithm and then use a JCA key factory
             * to re-create the key.
             */
        DerValue val = new DerValue(keyInfo);
        DerInputStream in = val.toDerInputStream();
        int i = in.getInteger();
        DerValue[] value = in.getSequence(2);
        AlgorithmId algId = new AlgorithmId(value[0].getOID());
        String keyAlgo = algId.getName();
        // decode private key
        if (entry instanceof PrivateKeyEntry) {
            KeyFactory kfac = KeyFactory.getInstance(keyAlgo);
            PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(keyInfo);
            key = kfac.generatePrivate(kspec);
            if (debug != null) {
                debug.println("Retrieved a protected private key (" + key.getClass().getName() + ") at alias '" + alias + "'");
            }
        // decode secret key
        } else {
            byte[] keyBytes = in.getOctetString();
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, keyAlgo);
            // Special handling required for PBE: needs a PBEKeySpec
            if (keyAlgo.startsWith("PBE")) {
                SecretKeyFactory sKeyFactory = SecretKeyFactory.getInstance(keyAlgo);
                KeySpec pbeKeySpec = sKeyFactory.getKeySpec(secretKeySpec, PBEKeySpec.class);
                key = sKeyFactory.generateSecret(pbeKeySpec);
            } else {
                key = secretKeySpec;
            }
            if (debug != null) {
                debug.println("Retrieved a protected secret key (" + key.getClass().getName() + ") at alias '" + alias + "'");
            }
        }
    } catch (Exception e) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
        uke.initCause(e);
        throw uke;
    }
    return key;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) DerValue(sun.security.util.DerValue) DerInputStream(sun.security.util.DerInputStream) SecretKeyFactory(javax.crypto.SecretKeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory) ObjectIdentifier(sun.security.util.ObjectIdentifier) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) DestroyFailedException(javax.security.auth.DestroyFailedException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKey(javax.crypto.SecretKey) AlgorithmId(sun.security.x509.AlgorithmId) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(sun.security.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) AlgorithmParameters(java.security.AlgorithmParameters)

Example 90 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project jdk8u_jdk by JetBrains.

the class Pair method recoverKey.

/**
     * Recovers (private) key associated with given alias.
     *
     * @return an array of objects, where the 1st element in the array is the
     * recovered private key, and the 2nd element is the password used to
     * recover it.
     */
private Pair<Key, char[]> recoverKey(String alias, char[] storePass, char[] keyPass) throws Exception {
    Key key = null;
    if (keyStore.containsAlias(alias) == false) {
        MessageFormat form = new MessageFormat(rb.getString("Alias.alias.does.not.exist"));
        Object[] source = { alias };
        throw new Exception(form.format(source));
    }
    if (!keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class) && !keyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
        MessageFormat form = new MessageFormat(rb.getString("Alias.alias.has.no.key"));
        Object[] source = { alias };
        throw new Exception(form.format(source));
    }
    if (keyPass == null) {
        // Try to recover the key using the keystore password
        try {
            key = keyStore.getKey(alias, storePass);
            keyPass = storePass;
            passwords.add(keyPass);
        } catch (UnrecoverableKeyException e) {
            // Did not work out, so prompt user for key password
            if (!token) {
                keyPass = getKeyPasswd(alias, null, null);
                key = keyStore.getKey(alias, keyPass);
            } else {
                throw e;
            }
        }
    } else {
        key = keyStore.getKey(alias, keyPass);
    }
    return Pair.of(key, keyPass);
}
Also used : MessageFormat(java.text.MessageFormat) UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyStore(java.security.KeyStore) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) PublicKey(java.security.PublicKey) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertStoreException(java.security.cert.CertStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException)

Aggregations

UnrecoverableKeyException (java.security.UnrecoverableKeyException)109 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)87 KeyStoreException (java.security.KeyStoreException)86 IOException (java.io.IOException)69 CertificateException (java.security.cert.CertificateException)58 KeyStore (java.security.KeyStore)30 InvalidKeyException (java.security.InvalidKeyException)29 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)29 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)27 BadPaddingException (javax.crypto.BadPaddingException)26 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)26 KeyManagementException (java.security.KeyManagementException)25 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)20 SSLContext (javax.net.ssl.SSLContext)20 SecretKey (javax.crypto.SecretKey)17 RemoteException (android.os.RemoteException)15 FileNotFoundException (java.io.FileNotFoundException)13 InputStream (java.io.InputStream)13 Key (java.security.Key)13 PrivateKey (java.security.PrivateKey)12