Java Generate CSR

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.

Java 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

Java Program to generate CSR

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 <https://www.journaldev.com>");
		System.out.println("CSR Request Generated!!");
		System.out.println(csr);
	}

}

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:  106387108829418419042369947333325674364935070884841588785129398089552939085654124805841484499579147437761572358957912128200485877657705616839322864387844152358079881259957155577261553853578965458427174717192288199902709049923855496876099206975440375817623502655106113446775789727649598690744221181544174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, 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 issue with it.

Comments

  1. Brian says:

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

    https://stackoverflow.com/q/8160606

    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.

      https://web.archive.org/web/*/https://www.journaldev.com/223/generating-a-certificate-signing-request-using-java-api

  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));

    with

    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:

    Hi,

    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.

    thanks

  7. thandar says:

    I have an error can not resolve the import sun.security.x509.X500Singer .

  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 sun.security 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();
    keyUsage.set(KeyUsageExtension.DATA_ENCIPHERMENT,true);
    System.out.println(keyUsage.toString());

    OutputStream out = new ByteArrayOutputStream();
    keyUsage.encode(out);

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

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

    //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”);
    System.out.println(“\nAttrs”+CSRinfo.getAttributes());

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

  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:

    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.

  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

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages