Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize and Deserialize an RSA public key

Tags:

java

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.

like image 583
weston Avatar asked Feb 06 '14 15:02

weston


1 Answers

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

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.

like image 98
Robert Avatar answered Sep 28 '22 04:09

Robert