title: Android: decrypt RSA text using a Public key stored in a file
body: <p>I've been several days trying to do it without success.</p>
  
  <p>There are plenty of similar questions here in StackOverflow and even two of them are exactly the same as mine but unanswered and unresolved:
  1) <a href="https://stackoverflow.com/questions/7037780/convert-php-rsa-publickey-into-android-publickey">Convert PHP RSA PublicKey into Android PublicKey</a>
  2) <a href="https://stackoverflow.com/questions/9823409/android-how-to-decrypt-an-openssl-encrypted-file-with-rsa-key">Android: how to decrypt an openssl encrypted file with RSA key?</a></p>
  
  <p>My scenario:
  I have some text encrypted using RSA (not encrypted by me). I have a "public.key" file in my res/raw folder with the public key needed to decrypt it (the public key related to the private key used to encrypt the message), with a format like the following example:
  <img src="https://i.stack.imgur.com/mR39v.png" alt="enter image description here"></p>
  
  <p>I see a lot of examples of how to decrypt a RSA text, like the following one:</p>
  
  <pre><code>public static byte[] decryptRSA( PublicKey key, byte[] text) throws Exception
        { 
            byte[] dectyptedText = null;
  
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            dectyptedText = cipher.doFinal(text);
            return dectyptedText;
        }
  </code></pre>
  
  <p>But my question is, how to get the proper PublicKey instance from the file? No examples of this.</p>
  
  <p>If I simply try:</p>
  
  <pre><code>    InputStream is = getResources().openRawResource(R.raw.public);
      DataInputStream dis = new DataInputStream(is);
      byte [] keyBytes = new byte [(int) is.available()];
      dis.readFully(keyBytes);
      dis.close();
      X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
      return keyFactory.generatePublic(spec);
  </code></pre>
  
  <p>I get an InvalidKeyException in the return sentence.
  Would I need to decode Hex or Base64? Aren't the first and last lines of the public key file a problem (the ones with "----BEGIN PUBLIC KEY----" and so)?</p>
  
  <p>Maybe we could get the answer of this properly for the first time in StackOverflow:-)</p>