AndroidKeyStore getEntry successively fails after a certain point

I use AndroidKeyStore to create RSA key pairs that are used to encrypt / decrypt internal data.

The code that does this is as follows: it tries to get an existing RSA key pair (via an alias). If none exists, it tries to generate a new one. the code is -

private void initializePublicPrivateKeys(){
    try
    {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(APP_RSA_KEY_PAIR_SECRET_ALIAS, null);
        _app_privateRSAKey = entry.getPrivateKey();
        _app_publicRSAKey = entry.getCertificate().getPublicKey();
    }
    catch(Exception e){

    }
}

private void initializeRSAKeyPairs() {

    initializePublicPrivateKeys();
    boolean isKeyNotGenerated = _app_privateRSAKey == null || _app_publicRSAKey == null;

    if(isKeyNotGenerated)
    {
        //Check here, if we already stored some data with previous RSA key pair - if a entry is present in SharedPreference then that would mean we had previously generated a RSA key pair and the entry is in-turn encrypted by this key pair.

        generateAppRSAPublicPrivateKeys();
        initializePublicPrivateKeys();// initialize it again , since we have new keys generated.
    }
}

@TargetApi(18)
private void generateAppRSAPublicPrivateKeys(){
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    // the certificate created would be valid for 25 years. This is just a random value.
    cal.add(Calendar.YEAR, 25);
    Date end = cal.getTime();

    try{
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        Context appContext = getApplicationContext();


        KeyPairGeneratorSpec.Builder keyPairGeneratorBuilder =
                new KeyPairGeneratorSpec.Builder(appContext)
                        .setAlias("myrsaalias")
                        .setStartDate(now)
                        .setEndDate(end)
                        .setSerialNumber(BigInteger.valueOf(1))
                        .setSubject(new X500Principal(String.format("CN=%s, OU=%s", "myrsaalias",
                                appContext.getApplicationInfo().packageName)));

        if(Build.VERSION.SDK_INT >= 19){
            keyPairGeneratorBuilder.setKeySize(2048); 
        }

        generator.initialize(keyPairGeneratorBuilder.build());
        generator.generateKeyPair();
    }
    catch(Exception e){
        e.printStackTrace();
        throw new IllegalArgumentException("Failed to generate RSA Public Private Key pair");
    }
}

. / ( ), ( ) initializePublicPrivateKeys ( ) , , , . ( , , , , )

, initializePublicPrivateKeys ?

PS: , - , , . , PIN- ( )

,

0

All Articles