views:

205

answers:

3

Hello everyone.

I want to implement a RSA algorithm to encrypt an image (byte[]). To generate my two keys I used this piece of code :

KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
keygen.initialize(512);
keyPair = keygen.generateKeyPair();

Once public and private key are generated, I would like to show them to the user so he can distribute the public key and use the private key to decode. How can I get back those key?

Using keygen.getPrivateKey() and keygen.getPublicKey() give me all the information of the RSA algorithm, not only the keys I need.

Thanks

A: 

You can use Key.getEncoded() to get the bytes of the key.

http://java.sun.com/j2se/1.4.2/docs/api/java/security/Key.html#getEncoded%28%29

WhirlWind
+3  A: 

Via the Relevant KeySpec classes, you can call the getModulus() and getPublicExponent()/getPrivateExponent() methods to pull out the key components:

KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
  RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
  RSAPrivateKeySpec.class);

saveToFile("public.key", pub.getModulus(),
  pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(),
  priv.getPrivateExponent());

In case it's useful, I wrote a few articles a while back dealing with some of the details of RSA encryption in Java (and Java-based cryptography generally.

Neil Coffey
Thanks a lot, your articles helped me a lot.
Robin Monjo
A: 

What you post doesn't make any sense since getPublicKey() and getPrivateKey() return exactly what you say you need. However, if you want to extract the components you should simply cast your PublicKey and PrivateKey to RSAPublicKey and RSAPrivateKey rather than going through the rigamorole of using KeySpecs.

Also, you'll soon find out that you cannot encrypt anything larger than 501 bytes using RSA with your plan, pretty much useless for images.

GregS