title: Load RSA public key from file
body: <p>I've generated a private key with:</p>
  
  <pre><code>openssl genrsa [-out file] –des3
  </code></pre>
  
  <p>After this I've generated a public key with:</p>
  
  <pre><code>openssl rsa –pubout -in private.key [-out file]
  </code></pre>
  
  <p>I want to sign some messages with my private key, and verify some other messages with my public key, using code like this:</p>
  
  <pre><code>public String sign(String message) throws SignatureException{
      try {
          Signature sign = Signature.getInstance("SHA1withRSA");
          sign.initSign(privateKey);
          sign.update(message.getBytes("UTF-8"));
          return new String(Base64.encodeBase64(sign.sign()),"UTF-8");
      } catch (Exception ex) {
          throw new SignatureException(ex);
      }
  }
  
  public boolean verify(String message, String signature) throws SignatureException{
      try {
          Signature sign = Signature.getInstance("SHA1withRSA");
          sign.initVerify(publicKey);
          sign.update(message.getBytes("UTF-8"));
          return sign.verify(Base64.decodeBase64(signature.getBytes("UTF-8")));
      } catch (Exception ex) {
          throw new SignatureException(ex);
      }
  }
  </code></pre>
  
  <p>I found a solution to convert my private key to PKCS8 format and load it. It works with some code like this:</p>
  
  <pre><code>public PrivateKey getPrivateKey(String filename) throws Exception {
  
      File f = new File(filename);
      FileInputStream fis = new FileInputStream(f);
      DataInputStream dis = new DataInputStream(fis);
      byte[] keyBytes = new byte[(int) f.length()];
      dis.readFully(keyBytes);
      dis.close();
      PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
      KeyFactory kf =
              KeyFactory.getInstance("RSA");
      return kf.generatePrivate(spec);
  }
  </code></pre>
  
  <p>And finally my question is: <strong>How do I load my RSA Public Key from a file?</strong></p>
  
  <p>I think maybe I need to convert my public key file to x509 format, and use <code>X509EncodedKeySpec</code>. But how can I do this?</p>