Serialize and Deserialize an RSA public key

java

Solution

Asymmetric keys like those from RSA are usually stored in X509 format. Therefor you can use `X509EncodedKeySpec`instead.

A simple example is already in the Java 7 JavaDoc (just replace DSA with RSA): http://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html

X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);

If you need to deserialize the private from `byte[]`, I've found that you must use `PKCS8EncodedKeySpec`.

Problem

``` 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 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.

Original source