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:  106387108829418419042369947333325674364935070884841588785129398089552939085654124805841484499579147437761572358957912128200485877657705616839322864387844152358079881259957155577261553853578965458427174717192288199902709049923855496876099206975440375817623502655106113446775789727649598690744221181544174782126
CSR Request Generated!!
-----BEGIN NEW CERTIFICATE REQUEST-----
MIIC1jCCAb4CAQAwgZAxDDAKBgNVBAYTA1VTQTETMBEGA1UECBMKQ2FsaWZvcm5pYTESMBAGA1UE
BxMJQ3VwZXJ0aW5vMRMwEQYDVQQKEwpKb3VybmFsRGV2MQ0wCwYDVQQLEwRKYXZhMTMwMQYDVQQD
DCpqb3VybmFsZGV2LmNvbSA8aHR0cDovL3d3dy5qb3VybmFsZGV2LmNvbT4wggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQDOQkjVbOyP5P43lQLO8u78NMhOoXBknXst3P0AFMgZoN/sR+SC
Pbz/RBJIV6vzhSi8nT9CMA+khYTi0QAiUYO3klNzmXpMnt0yy4QX/Lej4ybgHVrver1kKGINv/nc
iM2gI3huM1sUsQVdKbb4KmKHjJPo4DQFZqVJtRnh/Zs9Pq64kqrgktmqN8G2nrCdWu/RSX7JX5Yi
AdvPXyHi2ltvPXXGaO/dUCEGKfBbeYhi+6jYje64bXSg8Lblv0H10U8QXqpW4iyAeKMA9QTopa2s
Rgs6ypk0Jq4wVROCG+Z9ZBwaMKPlhCacVfFa82mxSI1OBUUyh3lbrF4E9RzxKhnBAgMBAAGgADAN
BgkqhkiG9w0BAQQFAAOCAQEAyFk6cRROYAiXEuoqvZ0oriNx7No618juirSzpLR3brYR1e1PqOKZ
a1amqR0+UeAOrz2PqkGYNPW4KP3mrPswm0quCEr1+e6JQzkr6W5NpnMbtMtxEe0bsvyr4H2FDSrO
mdtEm/p8+IccFFGEXFksWQaGvcJoI50dPB1yuSIvu6B8kuDimB2osrf0iCakQSq2x9yzwRZ/l4yf
Hstkv/uE0VCVGKwc69PSH6h8DE/GfqkZTUXnnSeV5JPw5tn1eS81pX0oSlOFtXDy4yUWi6+T6fE5
QZrc5xlRd0hLgFy6K+3JHqBGp8aEFuuPp+Na79EgrfZ44ZvV5gncLC9fXmTWbg==
-----END NEW CERTIFICATE REQUEST-----

Once we 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
Today's Special: Web Application Development eBook Free Download Now
Exclusive Offer: Oracle Technology Magazine for Developers Download Now