Search in sources :

Example 1 with StrongBoxUnavailableException

use of android.security.keystore.StrongBoxUnavailableException in project okta-oidc-android by okta.

the class BaseEncryptionManager method generateKeys.

private void generateKeys(Context context) {
    // Check if exist instead generate new private and public keys
    try {
        if (!mKeyStore.containsAlias(mKeyAlias)) {
            KeyPairGenerator keyPairGenerator;
            try {
                keyPairGenerator = createKeyPairGenerator();
                if (keyPairGenerator == null) {
                    throw new RuntimeException("KeyPairGenerator is null");
                }
            } catch (GeneralSecurityException e) {
                throw new RuntimeException("Failed initialize KeyPairGenerator", e.getCause());
            }
            KeyPair keyPair = null;
            try {
                generateKeyPair(context, keyPairGenerator, mKeyAlias, RSA_KEY_SIZE, mEncryptionPadding, mBlockMode, true, null);
                keyPair = keyPairGenerator.generateKeyPair();
            } catch (ProviderException exception) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    if (exception instanceof StrongBoxUnavailableException) {
                        generateKeyPair(context, keyPairGenerator, mKeyAlias, RSA_KEY_SIZE, mEncryptionPadding, mBlockMode, false, null);
                        keyPair = keyPairGenerator.generateKeyPair();
                    }
                } else {
                    throw new RuntimeException("Failed generate keys.", exception.getCause());
                }
            }
            if (keyPair == null) {
                throw new RuntimeException("Failed generate keys.");
            }
        }
    } catch (KeyStoreException e) {
        throw new RuntimeException("Keystore exception.", e.getCause());
    }
}
Also used : KeyPair(java.security.KeyPair) ProviderException(java.security.ProviderException) GeneralSecurityException(java.security.GeneralSecurityException) StrongBoxUnavailableException(android.security.keystore.StrongBoxUnavailableException) KeyPairGenerator(java.security.KeyPairGenerator) KeyStoreException(java.security.KeyStoreException)

Example 2 with StrongBoxUnavailableException

use of android.security.keystore.StrongBoxUnavailableException in project Auditor by GrapheneOS.

the class SubmitSampleJob method onStartJob.

@Override
public boolean onStartJob(final JobParameters params) {
    task = executor.submit(() -> {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(SUBMIT_URL).openConnection();
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setDoOutput(true);
            final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
            keyStore.load(null);
            keyStore.deleteEntry(KEYSTORE_ALIAS_SAMPLE);
            final KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEYSTORE_ALIAS_SAMPLE, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY).setAlgorithmParameterSpec(new ECGenParameterSpec(AttestationProtocol.EC_CURVE)).setDigests(AttestationProtocol.KEY_DIGEST).setAttestationChallenge("sample".getBytes());
            AttestationProtocol.generateKeyPair(builder.build());
            final Certificate[] certs = keyStore.getCertificateChain(KEYSTORE_ALIAS_SAMPLE);
            keyStore.deleteEntry(KEYSTORE_ALIAS_SAMPLE);
            Certificate[] strongBoxCerts = null;
            if (Build.VERSION.SDK_INT >= 28) {
                try {
                    builder.setIsStrongBoxBacked(true);
                    AttestationProtocol.generateKeyPair(builder.build());
                    strongBoxCerts = keyStore.getCertificateChain(KEYSTORE_ALIAS_SAMPLE);
                    keyStore.deleteEntry(KEYSTORE_ALIAS_SAMPLE);
                } catch (final StrongBoxUnavailableException ignored) {
                } catch (final IOException e) {
                    if (!(e.getCause() instanceof StrongBoxUnavailableException)) {
                        throw e;
                    }
                }
            }
            final Process process = new ProcessBuilder("getprop").start();
            try (final InputStream propertyStream = process.getInputStream();
                final OutputStream output = connection.getOutputStream()) {
                for (final Certificate cert : certs) {
                    output.write(BaseEncoding.base64().encode(cert.getEncoded()).getBytes());
                    output.write("\n".getBytes());
                }
                if (strongBoxCerts != null) {
                    output.write("StrongBox\n".getBytes());
                    for (final Certificate cert : strongBoxCerts) {
                        output.write(BaseEncoding.base64().encode(cert.getEncoded()).getBytes());
                        output.write("\n".getBytes());
                    }
                }
                ByteStreams.copy(propertyStream, output);
                final StructUtsname utsname = Os.uname();
                output.write(utsname.toString().getBytes());
                output.write("\n".getBytes());
                final Properties javaProps = System.getProperties();
                final Enumeration<?> javaPropNames = javaProps.propertyNames();
                while (javaPropNames.hasMoreElements()) {
                    final String name = (String) javaPropNames.nextElement();
                    final String value = javaProps.getProperty(name);
                    output.write(name.getBytes());
                    output.write("=".getBytes());
                    output.write(value.getBytes());
                    output.write("\n".getBytes());
                }
            }
            final int responseCode = connection.getResponseCode();
            if (responseCode != 200) {
                throw new IOException("response code: " + responseCode);
            }
        } catch (final GeneralSecurityException | IOException e) {
            Log.e(TAG, "submit failure", e);
            final String exceptionMessage = e.toString();
            final Context context = SubmitSampleJob.this;
            final String errorMessage = context.getString(R.string.sample_submission_notification_content_failure) + "<br><br><tt>" + exceptionMessage + "</tt>";
            final Spanned styledText = Html.fromHtml(errorMessage, Html.FROM_HTML_MODE_LEGACY);
            final NotificationManager manager = context.getSystemService(NotificationManager.class);
            final NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, context.getString(R.string.sample_submission_notification_channel), NotificationManager.IMPORTANCE_LOW);
            manager.createNotificationChannel(channel);
            manager.notify(NOTIFICATION_ID, new Notification.Builder(context, NOTIFICATION_CHANNEL_ID).setContentTitle(context.getString(R.string.sample_submission_notification_title_failure)).setContentText(styledText).setShowWhen(true).setSmallIcon(R.drawable.baseline_cloud_upload_white_24).setStyle(new Notification.BigTextStyle().bigText(styledText)).build());
            jobFinished(params, true);
            return;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        final Context context = SubmitSampleJob.this;
        final NotificationManager manager = context.getSystemService(NotificationManager.class);
        final NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, context.getString(R.string.sample_submission_notification_channel), NotificationManager.IMPORTANCE_LOW);
        manager.createNotificationChannel(channel);
        manager.notify(NOTIFICATION_ID, new Notification.Builder(context, NOTIFICATION_CHANNEL_ID).setContentTitle(context.getString(R.string.sample_submission_notification_title)).setContentText(context.getString(R.string.sample_submission_notification_content)).setShowWhen(true).setSmallIcon(R.drawable.baseline_cloud_upload_white_24).build());
        jobFinished(params, false);
    });
    return true;
}
Also used : Context(android.content.Context) Enumeration(java.util.Enumeration) NotificationManager(android.app.NotificationManager) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) StructUtsname(android.system.StructUtsname) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) IOException(java.io.IOException) Properties(java.util.Properties) KeyProperties(android.security.keystore.KeyProperties) KeyStore(java.security.KeyStore) Spanned(android.text.Spanned) URL(java.net.URL) Notification(android.app.Notification) NotificationChannel(android.app.NotificationChannel) HttpURLConnection(java.net.HttpURLConnection) StrongBoxUnavailableException(android.security.keystore.StrongBoxUnavailableException) Certificate(java.security.cert.Certificate)

Aggregations

StrongBoxUnavailableException (android.security.keystore.StrongBoxUnavailableException)2 Notification (android.app.Notification)1 NotificationChannel (android.app.NotificationChannel)1 NotificationManager (android.app.NotificationManager)1 Context (android.content.Context)1 KeyProperties (android.security.keystore.KeyProperties)1 StructUtsname (android.system.StructUtsname)1 Spanned (android.text.Spanned)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 GeneralSecurityException (java.security.GeneralSecurityException)1 KeyPair (java.security.KeyPair)1 KeyPairGenerator (java.security.KeyPairGenerator)1 KeyStore (java.security.KeyStore)1 KeyStoreException (java.security.KeyStoreException)1 ProviderException (java.security.ProviderException)1 Certificate (java.security.cert.Certificate)1