Search in sources :

Example 11 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project robovm by robovm.

the class ProtectionParameterImpl method test_initLjava_security_KeyStore$C.

/**
     * Test for <code>init(KeyStore keyStore, char[] password)</code> and
     * <code>getKeyManagers()</code>
     * Assertion: returns not empty KeyManager array
     */
public void test_initLjava_security_KeyStore$C() throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    if (!DEFSupported) {
        fail(NotSupportedMsg);
        return;
    }
    KeyManagerFactory[] keyMF = createKMFac();
    assertNotNull("KeyManagerFactory object were not created", keyMF);
    KeyStore ksNull = null;
    KeyManager[] km;
    for (int i = 0; i < keyMF.length; i++) {
        keyMF[i].init(ksNull, new char[10]);
        km = keyMF[i].getKeyManagers();
        assertNotNull("Result should not be null", km);
        assertTrue("Length of result KeyManager array should not be 0", (km.length > 0));
    }
    KeyStore ks;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
    } catch (KeyStoreException e) {
        fail(e.toString() + "default KeyStore type is not supported");
        return;
    } catch (Exception e) {
        fail("Unexpected: " + e.toString());
        return;
    }
    for (int i = 0; i < keyMF.length; i++) {
        try {
            keyMF[i].init(ks, new char[10]);
        } catch (KeyStoreException e) {
        }
        km = keyMF[i].getKeyManagers();
        assertNotNull("Result has not be null", km);
        assertTrue("Length of result KeyManager array should not be 0", (km.length > 0));
    }
}
Also used : KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) KeyManager(javax.net.ssl.KeyManager) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchProviderException(java.security.NoSuchProviderException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 12 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project robovm by robovm.

the class KeyManagerFactory2Test method checkResult.

private void checkResult(KeyManagerFactory keyMF) throws Exception {
    KeyStore kStore = null;
    ManagerFactoryParameters mfp = null;
    char[] pass = { 'a', 'b', 'c' };
    try {
        keyMF.init(kStore, null);
        fail("KeyStoreException must be thrown");
    } catch (KeyStoreException e) {
    }
    try {
        keyMF.init(kStore, pass);
        fail("UnrecoverableKeyException must be thrown");
    } catch (UnrecoverableKeyException e) {
    }
    try {
        keyMF.init(mfp);
        fail("InvalidAlgorithmParameterException must be thrown");
    } catch (InvalidAlgorithmParameterException e) {
    }
    assertNull("getKeyManagers() should return null object", keyMF.getKeyManagers());
    try {
        kStore = KeyStore.getInstance(KeyStore.getDefaultType());
        kStore.load(null, null);
    } catch (KeyStoreException e) {
        fail("default keystore is not supported");
        return;
    }
    keyMF.init(kStore, pass);
    mfp = new MyKeyManagerFactorySpi.Parameters(kStore, null);
    try {
        keyMF.init(mfp);
        fail("InvalidAlgorithmParameterException must be thrown");
    } catch (InvalidAlgorithmParameterException e) {
    }
    mfp = new MyKeyManagerFactorySpi.Parameters(kStore, pass);
    keyMF.init(mfp);
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) MyKeyManagerFactorySpi(org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi) ManagerFactoryParameters(javax.net.ssl.ManagerFactoryParameters)

Example 13 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project platform_frameworks_base by android.

the class AndroidKeyStoreProvider method loadAndroidKeyStorePublicKeyFromKeystore.

@NonNull
public static AndroidKeyStorePublicKey loadAndroidKeyStorePublicKeyFromKeystore(@NonNull KeyStore keyStore, @NonNull String privateKeyAlias, int uid) throws UnrecoverableKeyException {
    KeyCharacteristics keyCharacteristics = new KeyCharacteristics();
    int errorCode = keyStore.getKeyCharacteristics(privateKeyAlias, null, null, uid, keyCharacteristics);
    if (errorCode != KeyStore.NO_ERROR) {
        throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to obtain information about private key").initCause(KeyStore.getKeyStoreException(errorCode));
    }
    ExportResult exportResult = keyStore.exportKey(privateKeyAlias, KeymasterDefs.KM_KEY_FORMAT_X509, null, null, uid);
    if (exportResult.resultCode != KeyStore.NO_ERROR) {
        throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to obtain X.509 form of public key").initCause(KeyStore.getKeyStoreException(exportResult.resultCode));
    }
    final byte[] x509EncodedPublicKey = exportResult.exportData;
    Integer keymasterAlgorithm = keyCharacteristics.getEnum(KeymasterDefs.KM_TAG_ALGORITHM);
    if (keymasterAlgorithm == null) {
        throw new UnrecoverableKeyException("Key algorithm unknown");
    }
    String jcaKeyAlgorithm;
    try {
        jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm(keymasterAlgorithm);
    } catch (IllegalArgumentException e) {
        throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to load private key").initCause(e);
    }
    return AndroidKeyStoreProvider.getAndroidKeyStorePublicKey(privateKeyAlias, uid, jcaKeyAlgorithm, x509EncodedPublicKey);
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyCharacteristics(android.security.keymaster.KeyCharacteristics) ExportResult(android.security.keymaster.ExportResult) NonNull(android.annotation.NonNull)

Example 14 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project platform_frameworks_base by android.

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 15 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project platform_frameworks_base by android.

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);
        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)

Aggregations

UnrecoverableKeyException (java.security.UnrecoverableKeyException)99 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)77 KeyStoreException (java.security.KeyStoreException)76 IOException (java.io.IOException)60 CertificateException (java.security.cert.CertificateException)49 InvalidKeyException (java.security.InvalidKeyException)28 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)27 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)26 BadPaddingException (javax.crypto.BadPaddingException)26 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)26 KeyStore (java.security.KeyStore)24 KeyManagementException (java.security.KeyManagementException)19 RemoteException (android.os.RemoteException)15 SecretKey (javax.crypto.SecretKey)15 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)15 SSLContext (javax.net.ssl.SSLContext)14 FileNotFoundException (java.io.FileNotFoundException)13 Key (java.security.Key)12 NoSuchProviderException (java.security.NoSuchProviderException)11 PrivateKey (java.security.PrivateKey)11