Keys can be used for Data Encryption and Digital Signing. They can be generated by OpenSSL which i have talked about in a previous article.
Actually, the Java JDK also provides API for creating key pair.
import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; public class CreateKeyAndCert { public static void main(String[] args) { KeyPairGenerator kpg; try { // Create a 1024 bit RSA private key kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.genKeyPair(); Key publicKey = kp.getPublic(); Key privateKey = kp.getPrivate(); KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = (RSAPublicKeySpec) fact.getKeySpec(publicKey, RSAPublicKeySpec.class); RSAPrivateKeySpec priv = (RSAPrivateKeySpec) fact.getKeySpec(privateKey, RSAPrivateKeySpec.class); // Save the file to local drive saveToFile("c:\\public.key", pub.getModulus(), pub.getPublicExponent()); saveToFile("c:\\private.key", priv.getModulus(), priv.getPrivateExponent()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } } public static void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException { ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName))); try { oout.writeObject(mod); oout.writeObject(exp); } catch (Exception e) { throw new IOException("Unexpected error", e); } finally { oout.close(); } } }
Done =)
Reference: RSA encryption in Java
Hi,
if I copy & paste I get this exception:
java.security.spec.InvalidKeySpecException: Inappropriate key specification
at com.ibm.crypto.provider.RSAKeyFactory.engineGetKeySpec(Unknown Source)
at java.security.KeyFactory.getKeySpec(KeyFactory.java:164)
at rsaEncrypt.CreateKeyAndCert.main(CreateKeyAndCert.java:29)
LikeLike
Hi Oli,
i missed the RSAPublicKeySpec and RSAPrivateKeySpec casting @ line 27-28. i have updated the code. please try again.
thanks for pointing out the problem. =)
Kit
LikeLike
Hi, thanks
but after saving keys in files, in another application, I have to call these keys from same files, how can I call them and use for a new encryption?
Thanks
HES
LikeLike
are your two applications run on the same server? you can load the key thru the file path.
The following post should help
Save/Load Private and Public Key to/from a file
LikeLike
hi again,
I have already found this page. The problem is I will use RSA encryption. In this page, it uses X509 and PKCS8. Do not it create a problem?
LikeLike
I found a post about loading an RSA key. seems that you need to convert the file from PEM to DER.
hope this one could help.
How to load an RSA private key from a file?
LikeLike
isnot create nay file
LikeLike
did it throw any error?
LikeLike
After saving keys to file, Iam unable to read the key values, it is showing like this(see below):
”
¬í sr java.math.BigIntegerŒüŸ©;û I bitCountI bitLengthI firstNonzeroByteNumI lowestSetBitI signum[ magnitudet [Bxr java.lang.Number†¬•”à‹ xpÿÿÿÿÿÿÿÿÿÿÿþÿÿÿþ ur [B¬óøTà xp €„âQ?V¿Bh¸Ù±ªƒÞ˜È‘<=¹¯¶»8CÍòvªœWÞ5BÉÏåôæ¾pÑ¢vE„÷ýÜ‹¶‰YÅäô°<¨z("xÍ ï ªçë¨/çb²ÆÙQƒ<&„=bñÚàÿ2X÷–B u Ý›È/ÖmõQ˜úô`ueóWxsq ~ ÿÿÿÿÿÿÿÿÿÿÿþÿÿÿþ uq ~ x "
Pls reply me as soon as possible.
LikeLike
I guess there is exception being thrown, any error in the console?
LikeLike
I am also facing the same problem. Please reply if you have a solution…
LikeLike