KeyInfo's isInsideSecureHardware-method's return value seems to depend on device model, os version, and some other random factors.
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.
Is there a way to make sure that the key is stored in secure hardware?
Here is my current 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
Thanks!
Edit:
In sony support forum there is a topic about the same problem:
https://talk.sonymobile.com/t5/Android-development/hardware-backed-keystore/td-p/1154124
It was mentioned that following warning is printed to logs:
W keystore: Primary keymaster device failed to generate key, falling back to SW.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…