Alex February 2016

KeyPairGeneratorSpec deprecated

KeyPairGeneratorSpec is deprecated since API 23. How do you handle this warning?

Example code:

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpg.initialize(new KeyPairGeneratorSpec.Builder(context).build());

Answers


divegeek March 2016

Per the documentation, you should use KeyGenParameterSpec instead. For example (for an RSA signing key):

KeyPairGenerator kpg = KeyPairGenerator.getInstance(
        KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
        "mykey", KeyProperties.PURPOSE_SIGN)
        .setDigests(KeyProperties.DIGEST_SHA256)
        .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
        .build());

The additional options to set digest and padding mode are required. This is because, following good crypto security practices, AndroidKeyStore now locks down the ways a key can be used (signing vs decryption, digest and padding modes, etc.) to a specified set. If you try to use a key in a way you didn't specify when you created it, it will fail. This failure is actually enforced by the secure hardware, if your device has it, so even if an attacker roots the device the key can still only be used in the defined ways.

KeyGenParameterSpec also supports creating ECDSA, AES and HMAC keys, and allows you to place other restrictions on how the keys can be used. For example, if you use the setUserAuthenticationRequired method, it will be impossible to use the key unless the user is around to authenticate themselves.

Post Status

Asked in February 2016
Viewed 2,064 times
Voted 13
Answered 1 times

Search




Leave an answer