iamMehedi / Secured-Preference-Store

A cryptography library and a SharedPreferences wrapper for Android that encrypts the content with 256 bit AES encryption. The Encryption key is securely stored in device's KeyStore.
562 stars 97 forks source link

Suggestion: it would be nice to know if key is inside secure hardware #24

Closed AlvaroBro closed 6 years ago

AlvaroBro commented 6 years ago

I think it would be nice to offer an easy way to someone using your library to know if the key used for encryption is currently stored in secure hardware. In my case I'd like to have this information to show it to the user and let him know that his data base is encrypted but it may (or may not) be 100% secure as his hardware supports (or not) TrustZone or whatever secure system.

I don't know if this is out of the scope of this library but its just a suggestion.

In my case I created a class copying your EncryptionManager class and adding a couple of functions. Please note that this was a fast guess and I haven't checked if there is a better way to determine or another way to determine it in API lower than 23, for example.

public static boolean isHardwareBacked(Context appContext) throws Exception {
        SharedPreferences prefs = appContext.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
        EncryptionManager mEncryptionManager = new EncryptionManager(appContext, prefs);
        return mEncryptionManager.isHardwareBacked();
    }

    @SuppressLint("NewApi")
    public boolean isHardwareBacked() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return false;
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return false; // Can't determine as KeyInfo is API 23
        }

        if (aesKey != null) {
            SecretKey key = aesKey;
            try {
                SecretKeyFactory factory = SecretKeyFactory.getInstance(
                        key.getAlgorithm(), "AndroidKeyStore");
                KeyInfo keyInfo = (KeyInfo) factory.getKeySpec(key, KeyInfo.class);
                return keyInfo.isInsideSecureHardware();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
iamMehedi commented 6 years ago

Thanks for the suggestion. I think it'll be a good addition to this library.