Implementing the RSA Algorithm in Java
I want to implement RSA algorithm for image encryption ( byte[]
). To generate my two keys, I used this piece of code:
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
keygen.initialize(512);
keyPair = keygen.generateKeyPair();
After generating the public and private keys, I would like to show them to the user so that he can distribute the public key and use the private key to decode. How can I get this key back?
Using keygen.getPrivateKey()
and keygen.getPublicKey()
, give me all the RSA algorithm information, not just the keys I need.
thanks
a source to share
With the appropriate 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 is useful, I have written several articles several times covering some details of RSA encryption in Java (and Java based cryptography.
a source to share
You can use Key.getEncoded () to get the key bytes.
http://java.sun.com/j2se/1.4.2/docs/api/java/security/Key.html#getEncoded%28%29
a source to share
What you are posting makes no sense at all, as getPublicKey () and getPrivateKey () return exactly what you say you want. However, if you want to extract components, you should just cast your PublicKey and PrivateKey into RSAPublicKey and RSAPrivateKey and not go through rigamorole with KeySpecs.
Also, you will soon find out that you cannot encrypt anything larger than 501 bytes using RSA with your plan, which is practically useless for images.
a source to share