Tuesday, March 24, 2015

Generate CSR in Java

PA CSR or Certificate Signing Request is a block of encrypted text that is generated on the server that the certificate will be used on. It contains information that will be included in your certificate such as your organization name, common name (domain name), locality, and country. It also contains the public key that will be included in your certificate. A private key is usually created at the same time that you create the CSR.

A certificate authority will use a CSR to create your SSL certificate, but it does not need your private key. You need to keep your private key secret. What is a CSR and private key good for if someone else can potentially read your communications? The certificate created with a particular CSR will only work with the private key that was generated with it. So if you lose the private key, the certificate will no longer work.

This article will show you how to generate CSR in Java.

What will we do?

  • Generate Keypair to obtain the Private Key and Public Key.
  • Package the necessary information for CSR and use Private Key sign on it. 

Coding time

package com.it4shared.gencsr;

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", "Java tutorial", "it-shared.com",
                "California", "US");
        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 = "SHA1WithRSA";
        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("it-4shared.com ");
        System.out.println("CSR Request Generated!!");
        System.out.println(csr);
    }
 
}
Which JRE version are you using?

A little bit different between jre 6 and jre 7 when you compile above source code.
If you use jre 7, you will meet error at line 80. So, need to be change likes that

pkcs10.encodeAndSign(x500Name, signature);

Access restriction?

If you meet this error
Access restriction on class due to restriction on required library rt.jar

Don't worry, follow this post will solve your doubt: How to use security token with SunPKCS11
Result:
Public Key:
Sun RSA public key, 2048 bits
  modulus: 19257207091825903467956315158723391899488308330132045583200286325612347332535086558206008961138104081229683751617734086462108005404147757373221546303174073782221524624663743733137293118804642576754211011016378744661501795576358879760626588692993482180681014044406521310609536437986345390932449865696305113759679659525664537209643897958780342733357237621431519275520146740782091893974820651212176881168551585627815201259935642909620627195097406549992857927603700719938530129507093704988311911587466889622586204313257180129127988524875791234151024204084557862706777473491496315685690849452176875303556203545098513831973
  public exponent: 65537
Private Key:
Sun RSA private CRT key, 2048 bits
  modulus:          19257207091825903467956315158723391899488308330132045583200286325612347332535086558206008961138104081229683751617734086462108005404147757373221546303174073782221524624663743733137293118804642576754211011016378744661501795576358879760626588692993482180681014044406521310609536437986345390932449865696305113759679659525664537209643897958780342733357237621431519275520146740782091893974820651212176881168551585627815201259935642909620627195097406549992857927603700719938530129507093704988311911587466889622586204313257180129127988524875791234151024204084557862706777473491496315685690849452176875303556203545098513831973
  public exponent:  65537
  private exponent: 2783813418190619183902499806426070995861150695327387580378099587238527528395218121861600758317017838252743089595593523279094423656848739694430641159593377405324728386927450266685120084952853865330567391219756354836551383360398309761694558818338041872221370020853981459278190155385242477282970383563586899732311853899623497405928076441517903760180474928793248628828754448487336682275751051021838961212440307381068644851436310421836191225424578775215867826169004445462764062481676308203696424556266358858686201176880163788253425032797395259659903439818757113893472931375810785783487361222830419073932373897048442536449
  prime p:          169794671408511140392706269775175031159390685459349906887729057952716762533744955941051283491433241967732738235159355343037708649379582253614206344883522591412008437870183780071400873398090675229391111420031401568118685947628077228009448051722575942234847218706313259375157623859724980789891716857192612053569
  prime q:          113414672746088398541001088650633320632743979636605152087127384062794579793841514268564905152345235697965534839365534335014577365577374730057949690843669331577696658613728564272446970620869948769201260665107212570850476698585808461247012954620596552809218042036976230482750748026414616188954122734890936767717
  prime exponent p: 83269004365008286192861734754018729900099434375444497114173854808738830703794236598339689815137470388374966917588868589121137006440022790655058851100239804812273237913662613355735295650008915602981984543689965155550827263328599144120476377959985821496681105470511438673078810913706164191023693177749523954433
  prime exponent q: 53079250537376189939264619849737174579970449416573130061131439095076603314718509020025676653382563579779344257335851032600929504813910275422088788280773086014787248622919610652982185374419382465613944292844781176634966832461417475981024174803896081110889051762487372650059217594125289649321770183630236546369
  crt coefficient:  22627559854384748872439261257649913611260962127344877457040949619018920842555330549405771343927369179585682405889416290866910114525013884822425546833852118939372215521341257434019929228915416662897809396503272657439129844461902188812667165357101583442000219847545758625783360809746708638229828638100188254455
CSR Request Generated!!
-----BEGIN NEW CERTIFICATE REQUEST-----
MIIC3DCCAcQCAQAwgZYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH
Ew1pdC1zaGFyZWQuY29tMRYwFAYDVQQKEw1KYXZhIHR1dG9yaWFsMQ0wCwYDVQQLEwRKYXZhMTMw
MQYDVQQDDCppdC00c2hhcmVkLmNvbSA8aHR0cDovL3d3dy5pdC00c2hhcmVkLmNvbT4wggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYi+UW7iENy/lKoqSb5VQBcaKB2+0mGsFnDJcc3ZPF
eFLP60Tol1y9lH4yiUAz4zQgEODBf/jQP21P+rxTcLlniYp+NIohhKNkSDK4fIWhejCh4RRsntsL
1hehYcgwQcEuHN2HkyEpboCTvpY/72D/KNc3lWk2KggNCrdpD/+V9q91dC/QsQF/SEKT1FY6/3Z5
y9swRuuSD6vuwhL078Flu1kdnJ9PDwUE6D7Gz4cI5gAZYiRDy8ZgbIbcjpY/MP5LdWoDjWD8RubR
MI7y+3dRJks6jg7vf2AIsQWXGf7mUgn7To+ugM/86TagZhJEUEy7bvYuIoEQ0/M18AokQFglAgMB
AAGgADANBgkqhkiG9w0BAQUFAAOCAQEAeT5+X9jRPEB6JeUkO6Td4Vul/bOZW0RfkITyy38zsOYU
dMa+eigZ+ta3qQU6W9AE0qFh6V8Vb1BbDeMukK4c/tKKyybIuu7kyJ7reZeEN3jzSVP3uh1V/qmH
DpiINOB4nz9ty/5rSN8VR4xlk8iSzucW3E6fe4sqb8ZVxpQiSZHfvTBnJ17dFbE1bae61rL9uIqc
53ixbg/bRkC26bjvEHBYiJeAsyszh7Xo5Vks93JwKgCW+X2ano+DwUtJsO0Gjiwbbv6tjuE1/s+n
bn7+4c8h3P+QU5c7J85E5NfkQsfJzVap0jJxdL0O76a+e5UOjSwhbvGDSq18PQZZo8fm5A==
-----END NEW CERTIFICATE REQUEST-----
You can copy CSR part and verify it at site: https://www.sslshopper.com/csr-decoder.html

1 comment: