title: Load public key data from file
body: <p>In my App I generate a public/private key pair and store them for later usage on disk. Loading and re-initialising the private key works fine but for the private key I get a Unknown KeySpec type: java.security.spec.PKCS8EncodedKeySpec - and I have no idea why.</p>
  
  <p>That's how I create and save the keys (code a bit simplified to be easier to read):</p>
  
  <pre><code>KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(4096);
  KeyPair keyPair = kpg.generateKeyPair();
  privKey =keyPair.getPrivate();
  pubKey =keyPair.getPublic();        
  
  DataOutputStream out=new DataOutputStream(ctx.openFileOutput(PRIVKEY_FILE,Context.MODE_PRIVATE));
  byte[] data=privKey.getEncoded();
  out.write(data);
  out.close();
  
  DataOutputStream out=new DataOutputStream(ctx.openFileOutput(PUBKEY_FILE,Context.MODE_PRIVATE));
  byte[] data=pubKey.getEncoded();
  out.write(data);
  out.close();
  </code></pre>
  
  <p>Next loading of the private key works fine:</p>
  
  <pre><code>DataInputStream in=new DataInputStream(ctx.openFileInput(PRIVKEY_FILE));
  byte[] data=new byte[in.available()];
  in.readFully(data);
  
  PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(data);
  KeyFactory kf = KeyFactory.getInstance("RSA");
  privKey = kf.generatePrivate(keySpec);
  
  decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  decryptCipher.init(Cipher.DECRYPT_MODE, privKey);
  </code></pre>
  
  <p>Similar code for the public key fails miserably:</p>
  
  <pre><code>DataInputStream in=new DataInputStream(ctx.openFileInput(PUBKEY_FILE));
  byte[] data=new byte[in.available()];
  in.readFully(data);
  
  PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(data);
  KeyFactory kf = KeyFactory.getInstance("RSA");
  pubKey = kf.generatePublic(keySpec); --&gt; here the exception is thrown
  
  encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  encryptCipher.init(Cipher.ENCRYPT_MODE, pubKey);             
  </code></pre>
  
  <p>So what am I doing wrong? What is the proper way of loading a public keys data from disk?</p>
  
  <p>Thanks!</p>