Search in sources :

Example 21 with GeneralSecurityException

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

the class AccountManagerService method finishSessionAsUser.

@Override
public void finishSessionAsUser(IAccountManagerResponse response, @NonNull Bundle sessionBundle, boolean expectActivityLaunch, Bundle appInfo, int userId) {
    Bundle.setDefusable(sessionBundle, true);
    int callingUid = Binder.getCallingUid();
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "finishSession: response " + response + ", expectActivityLaunch " + expectActivityLaunch + ", caller's uid " + callingUid + ", caller's user id " + UserHandle.getCallingUserId() + ", pid " + Binder.getCallingPid() + ", for user id " + userId);
    }
    if (response == null) {
        throw new IllegalArgumentException("response is null");
    }
    // Account type is added to it before encryption.
    if (sessionBundle == null || sessionBundle.size() == 0) {
        throw new IllegalArgumentException("sessionBundle is empty");
    }
    // Only allow the system process to finish session for other users
    if (isCrossUser(callingUid, userId)) {
        throw new SecurityException(String.format("User %s trying to finish session for %s without cross user permission", UserHandle.getCallingUserId(), userId));
    }
    // Only allow system to finish session
    if (!isSystemUid(callingUid)) {
        String msg = String.format("uid %s cannot finish session because it's not system uid.", callingUid);
        throw new SecurityException(msg);
    }
    if (!canUserModifyAccounts(userId, callingUid)) {
        sendErrorResponse(response, AccountManager.ERROR_CODE_USER_RESTRICTED, "User is not allowed to add an account!");
        showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
        return;
    }
    final int pid = Binder.getCallingPid();
    final Bundle decryptedBundle;
    final String accountType;
    // First decrypt session bundle to get account type for checking permission.
    try {
        CryptoHelper cryptoHelper = CryptoHelper.getInstance();
        decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
        if (decryptedBundle == null) {
            sendErrorResponse(response, AccountManager.ERROR_CODE_BAD_REQUEST, "failed to decrypt session bundle");
            return;
        }
        accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
        // properly by #StartAccountSession.
        if (TextUtils.isEmpty(accountType)) {
            sendErrorResponse(response, AccountManager.ERROR_CODE_BAD_ARGUMENTS, "accountType is empty");
            return;
        }
        // update credentials flow, we should replace with the new values of the current call.
        if (appInfo != null) {
            decryptedBundle.putAll(appInfo);
        }
        // Add info that may be used by add account or update credentials flow.
        decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
        decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
    } catch (GeneralSecurityException e) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.v(TAG, "Failed to decrypt session bundle!", e);
        }
        sendErrorResponse(response, AccountManager.ERROR_CODE_BAD_REQUEST, "failed to decrypt session bundle");
        return;
    }
    if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
        sendErrorResponse(response, AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE, "User cannot modify accounts of this type (policy).");
        showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE, userId);
        return;
    }
    long identityToken = clearCallingIdentity();
    try {
        UserAccounts accounts = getUserAccounts(userId);
        logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH, TABLE_ACCOUNTS, callingUid);
        new Session(accounts, response, accountType, expectActivityLaunch, true, /* stripAuthTokenFromResult */
        null, /* accountName */
        false, /* authDetailsRequired */
        true) {

            /* updateLastAuthenticationTime */
            @Override
            public void run() throws RemoteException {
                mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
            }

            @Override
            protected String toDebugString(long now) {
                return super.toDebugString(now) + ", finishSession" + ", accountType " + accountType;
            }
        }.bind();
    } finally {
        restoreCallingIdentity(identityToken);
    }
}
Also used : Bundle(android.os.Bundle) GeneralSecurityException(java.security.GeneralSecurityException) GeneralSecurityException(java.security.GeneralSecurityException) RemoteException(android.os.RemoteException)

Example 22 with GeneralSecurityException

use of java.security.GeneralSecurityException in project java-chassis by ServiceComb.

the class TestHttpsClient method testGeneralSecurityException.

@Test
public void testGeneralSecurityException() {
    new MockUp<HttpsClient>() {

        @Mock
        private SSLContext createSSLContext(HttpsConfigInfoBean configBean) throws GeneralSecurityException, IOException {
            throw new GeneralSecurityException();
        }
    };
    HttpsConfigInfoBean oBean = new HttpsConfigInfoBean();
    Assert.assertNotNull(HttpsClient.getHttpsClient(oBean));
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) MockUp(mockit.MockUp) HttpsConfigInfoBean(io.servicecomb.foundation.common.entities.HttpsConfigInfoBean) Test(org.junit.Test)

Example 23 with GeneralSecurityException

use of java.security.GeneralSecurityException in project java-apns by notnoop.

the class SSLContextBuilder method withCertificateKeyStore.

public SSLContextBuilder withCertificateKeyStore(InputStream keyStoreStream, String keyStorePassword, String keyStoreType, String keyAlias) throws InvalidSSLConfig {
    try {
        final KeyStore ks = KeyStore.getInstance(keyStoreType);
        ks.load(keyStoreStream, keyStorePassword.toCharArray());
        return withCertificateKeyStore(ks, keyStorePassword, keyAlias);
    } catch (GeneralSecurityException e) {
        throw new InvalidSSLConfig(e);
    } catch (IOException e) {
        throw new InvalidSSLConfig(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) InvalidSSLConfig(com.notnoop.exceptions.InvalidSSLConfig) IOException(java.io.IOException) KeyStore(java.security.KeyStore)

Example 24 with GeneralSecurityException

use of java.security.GeneralSecurityException in project azure-sdk-for-java by Azure.

the class JsonWebKey method getRSAPublicKey.

/**
     * Get the RSA public key value.
     *
     * @param provider the Java security provider.
     * @return the RSA public key value
     */
private PublicKey getRSAPublicKey(Provider provider) {
    try {
        RSAPublicKeySpec publicKeySpec = getRSAPublicKeySpec();
        KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider) : KeyFactory.getInstance("RSA");
        return factory.generatePublic(publicKeySpec);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) KeyFactory(java.security.KeyFactory)

Example 25 with GeneralSecurityException

use of java.security.GeneralSecurityException in project android_frameworks_base by DirtyUnicorns.

the class OSUManager method loadKeyStore.

private static KeyStore loadKeyStore(File ksFile, Set<X509Certificate> diskCerts) throws IOException {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        if (ksFile.exists()) {
            try (FileInputStream in = new FileInputStream(ksFile)) {
                keyStore.load(in, null);
            }
            // Note: comparing two sets of certs does not work.
            boolean mismatch = false;
            int loadCount = 0;
            for (int n = 0; n < 1000; n++) {
                String alias = String.format("%s%d", CERT_WFA_ALIAS, n);
                Certificate cert = keyStore.getCertificate(alias);
                if (cert == null) {
                    break;
                }
                loadCount++;
                boolean matched = false;
                Iterator<X509Certificate> iter = diskCerts.iterator();
                while (iter.hasNext()) {
                    X509Certificate diskCert = iter.next();
                    if (cert.equals(diskCert)) {
                        iter.remove();
                        matched = true;
                        break;
                    }
                }
                if (!matched) {
                    mismatch = true;
                    break;
                }
            }
            if (mismatch || !diskCerts.isEmpty()) {
                Log.d(TAG, "Re-seeding Passpoint key store with " + diskCerts.size() + " WFA certs");
                for (int n = 0; n < 1000; n++) {
                    String alias = String.format("%s%d", CERT_WFA_ALIAS, n);
                    Certificate cert = keyStore.getCertificate(alias);
                    if (cert == null) {
                        break;
                    } else {
                        keyStore.deleteEntry(alias);
                    }
                }
                int index = 0;
                for (X509Certificate caCert : diskCerts) {
                    keyStore.setCertificateEntry(String.format("%s%d", CERT_WFA_ALIAS, index), caCert);
                    index++;
                }
                try (FileOutputStream out = new FileOutputStream(ksFile)) {
                    keyStore.store(out, null);
                }
            } else {
                Log.d(TAG, "Loaded Passpoint key store with " + loadCount + " CA certs");
                Enumeration<String> aliases = keyStore.aliases();
                while (aliases.hasMoreElements()) {
                    Log.d("ZXC", "KS Alias '" + aliases.nextElement() + "'");
                }
            }
        } else {
            keyStore.load(null, null);
            int index = 0;
            for (X509Certificate caCert : diskCerts) {
                keyStore.setCertificateEntry(String.format("%s%d", CERT_WFA_ALIAS, index), caCert);
                index++;
            }
            try (FileOutputStream out = new FileOutputStream(ksFile)) {
                keyStore.store(out, null);
            }
            Log.d(TAG, "Initialized Passpoint key store with " + diskCerts.size() + " CA certs");
        }
        return keyStore;
    } catch (GeneralSecurityException gse) {
        throw new IOException(gse);
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

GeneralSecurityException (java.security.GeneralSecurityException)1197 IOException (java.io.IOException)448 Cipher (javax.crypto.Cipher)148 Test (org.junit.Test)136 X509Certificate (java.security.cert.X509Certificate)130 KeyStore (java.security.KeyStore)98 SSLContext (javax.net.ssl.SSLContext)86 SecretKeySpec (javax.crypto.spec.SecretKeySpec)82 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)77 ArrayList (java.util.ArrayList)75 File (java.io.File)64 InputStream (java.io.InputStream)63 Certificate (java.security.cert.Certificate)61 PublicKey (java.security.PublicKey)56 FileInputStream (java.io.FileInputStream)54 PrivateKey (java.security.PrivateKey)51 BigInteger (java.math.BigInteger)50 SecretKey (javax.crypto.SecretKey)48 IvParameterSpec (javax.crypto.spec.IvParameterSpec)47 KeyPair (java.security.KeyPair)45