title: Java RSA encryption with public key
body: <p>I'm trying to encrypt a file with a public key I get from a certificate.</p>
  
  <pre><code>PublicKey publicKey = cert.getPublicKey();
  cipher = Cipher.getInstance("RSA", "BC");        
  cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  </code></pre>
  
  <p>throws an exception: java.lang.IllegalArgumentException: not an RSA key!</p>
  
  <p>I've tried :</p>
  
  <pre><code>KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey.getEncoded());
  PublicKey rsaPublicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
  </code></pre>
  
  <p>but that throws <code>java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException</code>: Invalid RSA public key</p>
  
  <p>The constractor of <code>org.bouncycastle.asn1.pkcs.RSAPublicKey</code> expects 2 <code>BigInteger</code>s (probably the <em>modulus</em> and the <em>public exponent</em>).</p>
  
  <p>Looking into <code>cert.getPublicKey()</code> reveals its a <code>DSAPublicKeyImpl</code>.</p>
  
  <p>How can I convert it into an <code>RSAPublicKey</code> (or anything else) usable by <code>Cipher.getInstance("RSA", "BC")</code>?</p>