You can persist your RSA public/private key using SharedPreference on android.
In order to keep your keys safe when the phone is maliciously rooted, you can do the following steps:
1: When you want to ecrypt any data generate a key pair.
2: Prompt the user for a password.
3: Use that password to generate a symmetric key to encrypt your private key.
4: You can encrypt your data using the public key and decrypt using private key.
5: You can keep a session for the password prompted in step 2. During that session, you can use the symmetric key(generated from password) to encrypt/decrypt the private key.
The following code snippet shows to how to store & fetch the public key
public void setPublicKey(PublicKey publicKey, String key, Context context) {
byte[] pubKey = publicKey.getEncoded();
String pubKeyString = Base64.encodeBytes(pubKey);
this.setString(key, pubKeyString, context);
}
public PublicKey getPublicKey(String key,Context context) {
PublicKey pKey = null;
try {
String pubString = this.getString(key, context);
if(pubString!=null) {
byte[] binCpk = Base64.decode(pubString);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binCpk);
pKey = keyFactory.generatePublic(publicKeySpec);
}
}catch(Exception e){
}
return pKey;
}
The following code snippet shows how to store& fetch the private key.
public void setPrivateKey(PrivateKey privateKey, String key, Context context) {
byte[] priKey = privateKey.getEncoded();
String priKeyString = Base64.encodeBytes(priKey);
this.setString(key, priKeyString, context);
}
public PrivateKey getPrivateKey(String key, Context context) {
PrivateKey privateKey = null;
try {
String privateString = this.getString(key, context);
if(privateString!=null){
byte[] binCpk = Base64.decode(privateString);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binCpk);
privateKey = keyFactory.generatePrivate(privateKeySpec);
}
}
catch(Exception e){
}
return privateKey;
}