javaandroidencryptionrsastring-decoding

How to Decode RSA public key(in java) from a text view in Android studio


I am trying to create a RSA text encryption app for android so I create three fragments Generate,Encrypt,Decrypt in which i generated publickey,privatekey in generate fragment then encoded it with BASE64 and displayed it in text view(now user1 shares it with his friend user2 he then goes to his app and pastes the key in Encrypt Fragment textview).

Now in Encrypt Fragment I had taken the taken encoded public key value from text view to a string but i am not able to decode it to public key

Generating,Encoding code is

KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
               kpg.initialize(256);
               KeyPair kp=kpg.genKeyPair();
               publicKey=kp.getPublic();
               privateKey=kp.getPrivate();

 byte[] pubByte = publicKey.getEncoded();
 pubKeyStr = new String(Base64.encodeToString(pubByte,Base64.DEFAULT));

 byte[] priByte = privateKey.getEncoded();
 priKeyStr = new String(Base64.encodeToString(priByte,Base64.DEFAULT));
 return pubKeyStrr;

now we display pubKeyStr value in text view

In Encrypt Fragment i have taken pubKetStr value from textview as

   String str1=editText.getText().toString();

please anyone suggest how to decode this string str1 to convert it to RSA public key


Solution

  • If you have the key in a textfield encoded in base64, first convert it to byte[] and then generate the PublicKey

    byte publicKeyData[] = Base64.decode(str1, Base64.DEFAULT)
    X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyData);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey publicKey = kf.generatePublic(spec);