I am trying to use encryption data using RSA. So far so good. I can generate Private-Public keys, I can encrypt and decrypt the string successfully. Now I want to save the public key in SharedPreference. I can save it as a string. I can get it as a string. I need to convert it to Key in order to go to cipher. Conversion from String to the original format does not occur.
This is what I tried
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keypair=keyPairGenerator.generateKeyPair();
Cipher cipher =Cipher.getInstance("RSA/ECB/PKCS1Padding");
SharedPreferences sharedPreferences=context.getSharedPreferences("rsakey", MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("public",keypair.getPublic().toString());
editor.putString("private",keypair.getPrivate().toString());
editor.commit();
final String sampletext="abcde";
String publicKey = sharedPreferences.getString("public", null);
String privateKey = sharedPreferences.getString("private", null);
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] encryptedtext=cipher.doFinal(sampletext.getBytes());
String encrypted_text=new String(Base64.encode(encryptedtext,Base64.NO_WRAP));
cipher.init(Cipher.DECRYPT_MODE,privateKey);
encryptedtext=Base64.decode(encrypted_text.getBytes(), Base64.NO_WRAP);
encryptedtext=cipher.doFinal(encryptedtext);
String decrypted_text=new String(encryptedtext);
Here I ran into a problem in cipher.init (Cipher.ENCRYPT_MODE, publicKey); publicKey contains the saved PublicKey extracted from SahredPreferences. This is a String type! How to convert it to Key?
PS: , , .