```
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();

```

I want to create just the public key from a `byte[]`.

I have tried this as an experiment:

```
publicKey = new SecretKeySpec(publicKey.getEncoded(), publicKey.getAlgorithm());

```

But decryption using that key then fails.

I have also tried serializing the key with `ObjectOutputStream`, but serialization fails.

> 
> java.io.NotSerializableException: org.apache.harmony.xnet.provider.jsse.OpenSSLKey
> 
> 
> 

I read [here](http://www.coderanch.com/t/522854/java-io/java/serialize-java-security-key) that I can't use `SecretKeySpec` with RSA.

> 
> so as long as you are talking of a SecretKey and not an RSA or DSA key then you don't have to go through any contortions involving KeyGenerator or the like. 
> 
> 
> 

Anyone know how to perform these contortions or a way of doing this.