Search code examples
androidpasswordskeystore

Missing return statement after catch{throw..} implementation


It says missing return statement even tho it has return in try block. I do not understand it. I am trying to make an android app and and also store the login credentials for that app with android keystore. Also if anyone can give me an example of simple keystore implementation, that would be great. I found 2 example and they are not very understandable(missing codes) and also hard to implement to my situation.

private SecretKey createKey() {
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            keyGenerator.init(new KeyGenParameterSpec.Builder("Key", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setUserAuthenticationRequired(true)            //burayı kaldırırsan screen locka gerek kalmaz
                    .setUserAuthenticationValidityDurationSeconds(5)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                    .build());
            return keyGenerator.generateKey();
        }
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        throw new RuntimeException("Failed to create a symmetric key", e);
    }

}

Solution

  • The issue is you don't have a return if your Build.VERSION.SDK_INT >= Build.VERSION_CODES.M condition isn't met.

    private SecretKey createKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // ...
                return keyGenerator.generateKey();
            }
            // add a return here if we're not on >= Android M.
        } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
            throw new RuntimeException("Failed to create a symmetric key", e);
        }
        // you could also have a return here.
    }