0

I'm using this code to generate my RSA key pair under Api Level >= 23

 KeyPairGenerator spec = KeyPairGenerator.getInstance(
                            KeyProperties.KEY_ALGORITHM_RSA, Constants.KEYSTORE_NAME);

                    KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(
                            keyStoreAlias, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
                            .setKeySize(2048)
                            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                            .setKeyValidityStart(notBefore.getTime())
                            .setKeyValidityEnd(notAfter.getTime())
                            .setCertificateSubject(new X500Principal("CN=test"))
                            .setCertificateSerialNumber(BigInteger.ONE)
                            .build();

                    spec.initialize(keyGenParameterSpec);
KeyPair keyPair = spec.generateKeyPair();

If I try to build this code under api level < 23 compiler says "Call requires at least api level 23".

How can I convert this code to make it work with api level < 23?

setKeySize, setEncryptionPaddings .. these functions are not available api level < 23. How can I set encryption paddings for example in api level 14?

Trax
  • 943
  • 2
  • 12
  • 30
  • Which not tell us which call and which line the error is referring to? – President James K. Polk Mar 05 '20 at 01:23
  • As can be seen from the docs, the [`KeyProperties`](https://developer.android.com/reference/android/security/keystore/KeyProperties) class was not added until API 23. So just hardcode the constants (the values are again all provided in the documentation) or create your own class with the constants. – President James K. Polk Mar 05 '20 at 01:26
  • @PresidentJamesMoveonPolk .setKeySize(), .setEncryptionPaddings() .. all of these requires API level 23. How can I set paddings in API level 14? – Trax Mar 05 '20 at 17:00
  • Api level 14 !!! I still had hair back then. Anyway, the `KeyGenParameterSpec` and methods `setKeySize` and so on are actually restrictions designed to improve security by only allowing certain operations on keys. Back in Api level 14 you can just do what you want. Generate keys with [KeyPairGenerator](https://developer.android.com/reference/java/security/KeyPairGenerator) – President James K. Polk Mar 05 '20 at 20:42

1 Answers1

-1

You could use Spongy-Castle for level < 23.

Check this answer for deeper knowledge on Android Crypto and JCE https://stackoverflow.com/a/9965964/2002591