Java – Creating an RSA key pair in Java

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

12 thoughts on “Java – Creating an RSA key pair in Java”

  1. 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)

    Like

    1. 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

      Like

  2. 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

    Like

      1. 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?

        Like

  3. 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Ñ¢v­E„÷ýÜ‹¶‰YÅäô°<¨z("xÍ ï ªçë¨/çb²ÆÙQƒ<&„=bñÚàÿ2X÷–B u Ý›È/ÖmõQ˜úô`ueóWxsq ~ ÿÿÿÿÿÿÿÿÿÿÿþÿÿÿþ uq ~ x "

    Pls reply me as soon as possible.

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.