In Android, how to ensure that Private Key is stored inside secure hardware
<p>KeyInfo's isInsideSecureHardware-method's return value seems to depend on device model, os version, and some other random factors.</p>

<p>For example when using Sony xperia z5 compact with older os version isInsideSecureHardware() could return true for some time and then suddenly start returning false for the same Private Key.
With the latest os version (32.2.A.0.224) it seems to return only false.
Huawei Nexus 6P returns always true.</p>

<p>Is there a way to make sure that the key is stored in secure hardware?</p>

<p>Here is my current code:</p>

<pre><code>KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
keyPairGenerator.initialize(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
                                    .setUserAuthenticationRequired(true)
                                    .setBlockModes(KeyProperties.BLOCK_MODE_ECB)
                                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                                    .build());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Check that private key is inside secure hardware
KeyFactory factory = KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
KeyInfo keyInfo = factory.getKeySpec(key, KeyInfo.class);
boolean secure = keyInfo.isInsideSecureHardware(); //  this usually returns false
</code></pre>

<p>Thanks!</p>

<p>Edit:
In sony support forum there is a topic about the same problem:
<a href="https://talk.sonymobile.com/t5/Android-development/hardware-backed-keystore/td-p/1154124" rel="noreferrer">https://talk.sonymobile.com/t5/Android-development/hardware-backed-keystore/td-p/1154124</a></p>

<p>It was mentioned that following warning is printed to logs:</p>

<blockquote>
  <p>W keystore: Primary keymaster device failed to generate key, falling back to SW.</p>
</blockquote>