Free Online Books and PDFs for Web Designers
Powered by MaxBlogPress  

Generating a Certificate Signing Request using Java API

Recently I had to write a program to generate Certificate Signing Request (CSR) using Java API. Here I am providing the steps I followed with Java Program to generate CSR. After that we will also make sure that its valid by validating it with verisign CSR validator tool.

Steps to generate CSR:

  1. Get instance of KeyPairGenerator instance using standard encryption algorithm. I am using RSA here.
  2. Initialize the instance by providing keysize and source of randomness.
  3. Generate the PrivateKey and PublicKey that will be used in generating CSR.
  4. Initialize PKCS10 using the PublicKey.
  5. Get instance of Signature using standard algorithm. I am using MD5WithRSA in my case.
  6. Initialize the signature object using the PrivateKey.
  7. Create X500Name object by passing Common Name, Organization Unit, Organization, Location, State and Country
  8. Encode and Sign the PKCS10 object using X500Signer, Signature and X500Name object
  9. Print the PKCS10 object to PrintStream. After that you can save it in file or print in console

Here is the java program that does all the above steps and generates CSR:

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;

import sun.security.pkcs.PKCS10;
import sun.security.x509.X500Name;
import sun.security.x509.X500Signer;

/**
 * This class generates PKCS10 certificate signing request
 *
 * @author Pankaj@JournalDev.com
 * @version 1.0
 */
public class GenerateCSR {
	private static PublicKey publicKey = null;
	private static PrivateKey privateKey = null;
	private static KeyPairGenerator keyGen = null;
	private static GenerateCSR gcsr = null;

	private GenerateCSR() {
		try {
			keyGen = KeyPairGenerator.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		keyGen.initialize(2048, new SecureRandom());
		KeyPair keypair = keyGen.generateKeyPair();
		publicKey = keypair.getPublic();
		privateKey = keypair.getPrivate();
	}

	public static GenerateCSR getInstance() {
		if (gcsr == null)
			gcsr = new GenerateCSR();
		return gcsr;
	}

	public String getCSR(String cn) throws Exception {
		byte[] csr = generatePKCS10(cn, "Java", "JournalDev", "Cupertino",
				"California", "USA");
		return new String(csr);
	}

	/**
	 *
	 * @param CN
	 *            Common Name, is X.509 speak for the name that distinguishes
	 *            the Certificate best, and ties it to your Organization
	 * @param OU
	 *            Organizational unit
	 * @param O
	 *            Organization NAME
	 * @param L
	 *            Location
	 * @param S
	 *            State
	 * @param C
	 *            Country
	 * @return
	 * @throws Exception
	 */
	private static byte[] generatePKCS10(String CN, String OU, String O,
			String L, String S, String C) throws Exception {
		// generate PKCS10 certificate request
		String sigAlg = "MD5WithRSA";
		PKCS10 pkcs10 = new PKCS10(publicKey);
		Signature signature = Signature.getInstance(sigAlg);
		signature.initSign(privateKey);
		// common, orgUnit, org, locality, state, country
		X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
		pkcs10.encodeAndSign(new X500Signer(signature, x500Name));
		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(bs);
		pkcs10.print(ps);
		byte[] c = bs.toByteArray();
		try {
			if (ps != null)
				ps.close();
			if (bs != null)
				bs.close();
		} catch (Throwable th) {
		}
		return c;
	}

	public PublicKey getPublicKey() {
		return publicKey;
	}

	public PrivateKey getPrivateKey() {
		return privateKey;
	}

	public static void main(String[] args) throws Exception {
		GenerateCSR gcsr = GenerateCSR.getInstance();

		System.out.println("Public Key:\n"+gcsr.getPublicKey().toString());

		System.out.println("Private Key:\n"+gcsr.getPrivateKey().toString());
		String csr = gcsr.getCSR("journaldev.com <http://www.journaldev.com>");
		System.out.println("CSR Request Generated!!");
		System.out.println(csr);
	}

}

Output of the above program is:

Public Key:
Sun RSA public key, 2048 bits
  modulus: 26037776931447606564301911668340264365588256441567542911840292792434765686548135174803514821500951717023344926363109981325787971173530460861040665091912998796384478140799338823102943709222572753753148575339745289589310512219456669632030578432457763671199859709589664660544809036295499123604464821071199542366028235019743704583980957653052817052242205738795726852117662538431560025502232067403973812417432679056018629884034887401784178882475333051653937425454311701777276170897597383690900044390393040515458476468213094755569309619160826096120016873070175904132213506407833344302003083256464971071054484747131864881601
  public exponent: 65537
Private Key:
Sun RSA private CRT key, 2048 bits
  modulus:          26037776931447606564301911668340264365588256441567542911840292792434765686548135174803514821500951717023344926363109981325787971173530460861040665091912998796384478140799338823102943709222572753753148575339745289589310512219456669632030578432457763671199859709589664660544809036295499123604464821071199542366028235019743704583980957653052817052242205738795726852117662538431560025502232067403973812417432679056018629884034887401784178882475333051653937425454311701777276170897597383690900044390393040515458476468213094755569309619160826096120016873070175904132213506407833344302003083256464971071054484747131864881601
  public exponent:  65537
  private exponent: 25298403709154489762858973211975444004809463618616275729043784180708243280233136325904277122448305560724148367046056291421653033438297841307774621822675009709913148757092004499746754407868174354456039926809796314446632225705877945213988725639946603590755180537220676670046710410838949024133510870905438180870021344643386623503140258259331165258679977643949695434716892555078931474566186812852195303180453022307659511062728632303963722257687210144573594944851724154252492929289772706338425317947078700779560698959421958188982734117978481433792183026113100173798691435911387913122160234329314926878622847731795776140273
  prime p:          175772254401264910103735582553464996137826598899089757178842916506359825653874202619059992928378254849255956739128172727658175365316963495288643832645710857312081444039722597527221721147856862890282813419318626764068614091314957197496400996624314942167102882712465353334798965180064268779720240407757331030471
  prime q:          148133600608016272198361816372419184094364458516977730263887349448789432076447173882622161964439974131740979311782046426986257528056562105443129953435093622007037350344528566939773240286670595412252905217001182077948314004352625954242085959642446078959820708573114242894350683858794188646565327136681214847031
  prime exponent p: 101053557552693276819026645703182234836520295303720095075826531701582701542436672509894295032659961338026854113201264812742492506742947504089072162693212897779950328036508659682784686656529149640356986801548548441591425328174389387479887647448173373681616528294555283014916084197544311138475963472290167669653
  prime exponent q: 131373439958178155434535994799849669925883868012325551038309054803584835606562134983379851041353436630987826717112411346709420022974861569686827275486435318954072125314321518648603083326088596465370147504807096826746904901978780318178410976186554938451602899487107222263842569041012494201987731263838527386653
  crt coefficient:  106387108829418419042369947333325674364935070884841588785129398089552939085654124805841484499579147437761572358957912128200485877657705616839322864387844152358079881259957155577261553853578965458427174717192288199902709049923855496876099206975440375817623502655106113446775789727649598690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have the CSR, we can validate it using Verisign CSR Validator online utility.

I hope the program help you in generating CSR easily. Let me know if you face any issue with it.

VN:F [1.9.12_1141]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.12_1141]
Rating: -1 (from 1 vote)

Incoming search terms:

java security csr,generating certificate signing request with java,generate certificate signing request java code,could not generate a csr,generatecsr(): could not generate a csr,java generate CSR,create csr through java code,java security creating csr,java create CSR,Generate CSR java
http://www.journaldev.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/dzone_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/blinklist_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/newsvine_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/google_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/sphinn_48.png http://www.journaldev.com/wp-content/plugins/sociofluid/images/twitter_48.png

Who reads this also read:

  1. Java Interview Questions: Understanding and Extending Java ClassLoader
  2. Java Program to Connect to Remote database through SSH using Port Forwarding
  3. HashMap implementation with List in Java
  4. Thread Safety in Java Singleton Classes with Example Code
  5. Read File in Java – Line by Line, Read by Number of Bytes, Count of String occurrence in File

4 comments to Generating a Certificate Signing Request using Java API

  • Andrei

    Thank you so much for this.
    I have spent some time searching for something like this. Not many examples out there.
    Thanks again

    VA:F [1.9.12_1141]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.12_1141]
    Rating: 0 (from 0 votes)
  • Tupac

    Hi:

    Thank you very much for this example.
    It’s been very useful for me.
    It worked fine generating a sigle CSR using User’s data recovered from a DB.

    But, now I have a question:
    When I tried to generate 10 CSRs for different Users stored in the DB,
    the CA tells me that I’m using the same Key for all the CSRs.
    I tried this using an EJBCA CA to batch-process these files.

    I guess it is something related to the initialization of the Secure Random.
    How can I fix it?

    Thank you in advance.

    VA:F [1.9.12_1141]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.12_1141]
    Rating: 0 (from 0 votes)
  • Tupac

    Well, I found an easy solution, sorry.
    To be focus in my CA server took me away from Java basics.
    Thank you.

    VA:F [1.9.12_1141]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.12_1141]
    Rating: 0 (from 0 votes)
  • Libor

    Hello, thanks for example.
    I want to make Java applet for generate CSR, but when I call constructor
    PKCS10 pkcs10 = new PKCS10(publickey)
    applet throw exception java.security.AccessControlException: access denied (java.lang.RuntimePermission accessClassInPackage.sun.security.pkcs)

    I have tried to sign applet but it’s the same. Can you help me?

    VA:F [1.9.12_1141]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.12_1141]
    Rating: 0 (from 0 votes)

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>