Robin Monjo
Robin Monjo

Reputation: 45

Implement a RSA algorithm in Java

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

Upvotes: 2

Views: 3357

Answers (3)

WhirlWind
WhirlWind

Reputation: 14112

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

Upvotes: 0

President James K. Polk
President James K. Polk

Reputation: 41967

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.

Upvotes: 0

Neil Coffey
Neil Coffey

Reputation: 21795

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.

Upvotes: 4

Related Questions