Java Generate CSR Programmatically

Filed Under: Java
java generate CSR, Java CSR

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 it’s valid by validating it with VeriSign CSR validator tool.

Steps to Generate CSR Programmatically in Java

  1. Get instance of KeyPairGenerator 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

Java Program to generate CSR

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



 * This class generates PKCS10 certificate signing request
 * @author
 * @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) {
		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);
		// 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);
		byte[] c = bs.toByteArray();
		try {
			if (ps != null)
			if (bs != null)
		} 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(" <>");
		System.out.println("CSR Request Generated!!");


The 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!!

Validating the CSR

Once we have the CSR, we can validate it using any CSR Validator online utility.

java generate CSR, Java CSR

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


  1. Brian says:

    Looks like a copy&paste from this 2014 post on StackOverflow…

    1. Pankaj says:

      Hi Brian,

      Did you even checked which one is older before accusing me of copying something? My post is from 2011, you can check in wayback machine itself.*/

  2. Tim Spears says:

    Thank you very much for sharing this.

    If anyone has a problem with the X500Signer, it is not required any more. Instead just replace the line

    pkcs10.encodeAndSign(new X500Signer(signature, x500Name));


    pkcs10.encodeAndSign(x500Name, signature);

  3. Shirin Khanna says:

    Hi Pankaj,

    Thanks for this example. Is there a way that the csr and the leypair can be stored inside a keystore. Although this seems basic I haven’t found code for this.

    Best Regards,
    Shirin Khanna

  4. ravinder says:

    I have generated the CSR file with above code. but i want to add the KeyUsage(KeyAgreement,EncipherOnly,DecipherOnly) in my CSR file. How i can proceed in this regard.

  5. Michel says:

    The code generates a CSR, OK, but it then completely forgets about the private key!
    Without it, the certificate you’ll obtain from the CA is completely useless.
    It makes really no sense to create a CSR without storing a self-signed certificate in a keystore along with the private key.
    The correct steps are:
    * Generate a keypair as above.
    * Generate a self-signed certificate.
    * Store the certificate along with the private key in a (password) protected keystore.
    * Generate the CSR and submit it to a CA for signing.
    * Once the CA returns the official certificate, create a certificate path.
    * Replace the self sgined certificate in the keystore with the complete path

  6. Ahsan Abid says:


    thanks for your explanation. it helped a lot.

    now i have a question.

    we need to import the certificate that was generated from this CSR request into a keystore.

    can you give us and example for that.


  7. thandar says:

    I have an error can not resolve the import .

  8. Ruchir Shah says:

    Can you please post the code of generating and verifying CSR using SHA1 and RSA?

  9. Arun says:

    Hi ,
    I have a query. Suppose i have CA certificate and CA key and i want to generate certificates using my CA. How to do that programmatically.

  10. Venkat Madhav says:

    Hi Pankaj, This post was very helpful. Thanks to you.
    Can you help me with generation of a CSR with additional attributes SubjectAltName and KeyUsage etc. I tried adding these attributes using PKCSAttributes class but it was of no avail.

    Thank You

    1. Pankaj says:

      I will look into it and if found a solution, I will post it here.

      1. Pankaj says:

        Can u try to use SubjectAlternativeNameExtension class for SubjectAltName?

        1. Usha says:

          Is it possible to post a solution related to Certificate signing Request containing SubjectAltName using sun.secuirty package?

          I found solutions using BouncyCastle but none whatsoever with packages.

  11. Sapan says:

    HI Pankaj,

    Thanks for the above solution.
    It would be of great help if you can suggest a way to add the keyUsage and SubAltname attributes. As i am using the IBM jars to have my compliant with FIPS.
    I am using below code to add the extra attribute but was not able to get the attribute’s value in generating the CSR
    X500Name x500Name = new X500Name(CN, OU, O, C);
    KeyUsageExtension keyUsage = new KeyUsageExtension();

    OutputStream out = new ByteArrayOutputStream();

    DerValue val = new DerValue(DerValue.tag_SetOf, ((ByteArrayOutputStream) out).toByteArray());

    PKCSAttribute attribute= new PKCSAttribute(new ObjectIdentifier(“”),val.toByteArray());
    PKCSAttributes attr = new PKCSAttributes(new PKCSAttribute[] {attribute});
    System.out.println(“i am here”);

    //PKCSAttributes attr=new PKCSAttributes(keyUsage.getExtensionValue());
    //PKCSAttributes attr=new PKCSAttributes(“IBMJCEFIPS”);
    String sigAlg = “SHA2WithRSA”;
    CertificationRequestInfo CSRinfo = new CertificationRequestInfo(x500Name,publicKey,attr,”IBMJCEFIPS”);
    CertificationRequest CSR = new CertificationRequest(CSRinfo, privateKey,sigAlg,”IBMJCEFIPS”);

    As i am able to see the attribute name in CSR but value of the attribute is null.

  12. Libor says:

    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 access denied (java.lang.RuntimePermission

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

  13. Tupac says:

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

  14. Tupac says:


    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.

  15. Andrei says:

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

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content