I am currently working on an android application based on client-server architecture. To ensure data security, I use a pair of Public-Private keys to encrypt and sign the data. I am using AndroidKeyStore to store a key pair. Below is the code for creating a key pair:
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder( mContext) .setAlias(mPrivateKeyAlias) .setSubject(new X500Principal("CN=" + mPrivateKeyAlias)) .setSerialNumber( BigInteger.valueOf(System.currentTimeMillis())) .setStartDate(start.getTime()) .setEndDate(end.getTime()).setKeySize(2048).build(); KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance( "RSA", "AndroidKeyStore"); kpGenerator.initialize(spec);
After executing this code, Keystore generates files (CERT and PKEY files) will be generated in the directory '/ data / misc / keystore / user_0 /'. I encrypt sensitive application data, such as auth-token, and store it in Shared Pref for security reasons.
But now, when the user changes the password or the output of the device, the key files are stored, since the master key used to encrypt the keystore is generated using the device credentials.
Now, to fix this problem, I tried to save the Public-Private key pair in RAM and when the password was changed. From the onPasswordChanged method (context context, intent) of the DeviceAdminReceiver method, I execute the code below:
KeyStore keyStore = KeyStore .getInstance("AndroidKeyStore"); keyStore.load(null); keyStore.setKeyEntry(mPrivateKeyAlias, mPrivateKey.getPrivateKey(), null, new Certificate[] { mPrivateKey.getCertificate() });
But after this code, only the CERT file is created in the directory '/data/misc/keystore/user_0/' and when decrypted using the private key, giving some invalid signature error.
In addition, I shared my public key with the server, encrypted data with the private key, so creating a new key pair would not be the best solution.
So, how can I save my batch of public private key after changing the device password? If there is no work, what is the exact use of AndroidKeyStore? Where can i use it?