title: read public key invalid key format java
body: <p>I have code:</p>
  
  <pre><code>public PublicKey read_public_key(String path)
                  throws IOException, NoSuchAlgorithmException,
                  InvalidKeySpecException {
  
           KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
              FileInputStream pubKeyStream = new FileInputStream(path);  
              byte[] pubKeyBytes = new byte[(int)path.length()];
              pubKeyStream.read(pubKeyBytes);   
              pubKeyStream.close();  
              X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes);   
              PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);  
  
              return pubKey;
          }
  </code></pre>
  
  <p>But I get <strong>invalid key format</strong> How do I get public key from .pub file? Later I need to: </p>
  
  <pre><code>private static byte[] encrypt(String text, PublicKey key) {
          byte[] cipherText = null;
          try {
            // get an RSA cipher object and print the provider
            final Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
            // encrypt the plain text using the public key
            cipher.init(Cipher.ENCRYPT_MODE, key);
            cipherText = cipher.doFinal(text.getBytes());
          } catch (Exception e) {
            e.printStackTrace();
          }
          return cipherText;
        }
  </code></pre>