Java Build CSR Create certificate __java

Source: Internet
Author: User
Tags base64 openssl stub
Java generates CSR, issuing certificate
Package Com.jinhill.cert;
Import Java.io.ByteArrayInputStream;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.math.BigInteger;
Import java.security.InvalidKeyException;
Import Java.security.KeyFactory;
Import Java.security.KeyPair;
Import Java.security.KeyPairGenerator;
Import Java.security.KeyStore;
Import java.security.NoSuchAlgorithmException;
Import java.security.NoSuchProviderException;
Import Java.security.PrivateKey;
Import Java.security.PublicKey;
Import Java.security.SecureRandom;
Import java.security.Security;
Import java.security.SignatureException;
Import java.security.cert.CertificateEncodingException;
Import java.security.cert.CertificateException;
Import java.security.cert.CertificateParsingException;
Import Java.security.cert.X509Certificate;
Import Java.security.spec.RSAPublicKeySpec;
Import java.util.Collection; Import JAVA.util.date;

Import Java.util.Iterator;

Import Javax.security.auth.x500.X500Principal;
Import org.bouncycastle.asn1.ASN1Sequence;
Import org.bouncycastle.asn1.DERBitString;
Import Org.bouncycastle.asn1.DEROutputStream;
Import Org.bouncycastle.asn1.DERSet;
Import Org.bouncycastle.asn1.pkcs.CertificationRequest;
Import Org.bouncycastle.asn1.pkcs.CertificationRequestInfo;
Import Org.bouncycastle.asn1.x500.X500Name;
Import Org.bouncycastle.asn1.x509.AlgorithmIdentifier;
Import Org.bouncycastle.asn1.x509.Certificate;
Import Org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
Import Org.bouncycastle.asn1.x509.X509CertificateStructure;
Import org.bouncycastle.asn1.x509.X509Extensions;
Import Org.bouncycastle.asn1.x509.X509Name;
Import Org.bouncycastle.cert.X509CertificateHolder;
Import Org.bouncycastle.cert.X509v3CertificateBuilder;
Import Org.bouncycastle.crypto.params.AsymmetricKeyParameter;
Import Org.bouncycastle.crypto.params.RSAKeyParameters; Import Org.bouncycastle.crypto.util.PrivateKeYfactory;
Import Org.bouncycastle.crypto.util.PublicKeyFactory;
Import Org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory;
Import Org.bouncycastle.jce.provider.BouncyCastleProvider;
Import Org.bouncycastle.openssl.PEMReader;
Import Org.bouncycastle.openssl.PEMWriter;
Import Org.bouncycastle.openssl.PasswordFinder;
Import Org.bouncycastle.operator.ContentSigner;
Import Org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder;
Import Org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder;
Import org.bouncycastle.operator.OperatorCreationException;
Import Org.bouncycastle.operator.bc.BcRSAContentSignerBuilder;
Import Org.bouncycastle.pkcs.PKCS10CertificationRequest;
Import org.bouncycastle.util.encoders.Base64;
Import Org.bouncycastle.x509.X509V1CertificateGenerator;
Import Org.bouncycastle.x509.X509V3CertificateGenerator;
Import Org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; Import Org.bouncycastle.x509.extension.SubjectKeyIdentifieRstructure;
	public class CA {public CA () {Security.addprovider () (New Bouncycastleprovider ());
		public static string Getsubjectdn (Byte[] der {string DN = "";
			try {bytearrayinputstream bIn = new Bytearrayinputstream (der);
			Bouncycastleprovider Provider = new Bouncycastleprovider ();
			Certificatefactory CF = Certificatefactory.getinstance ("X509",//Provider);
			Certificatefactory CF = new certificatefactory ();
			X509Certificate cert = (x509certificate) cf. enginegeneratecertificate (bIn);
			DN = Cert.getsubjectdn (). GetName ();
		Bin.close ();
		catch (Certificateexception e) {e.printstacktrace ();
		catch (IOException e) {e.printstacktrace ();
	} return DN;
		public static string Parsecertdn (string dn, String type) {type = type + ' = ';
		string[] split = Dn.split (",");
				for (String x:split) {if (X.contains (type)) {x = X.trim ();
			Return x.substring (Type.length ());
	} return null; public string GENCSR (stringSubject, String Pempath, String pempassword) throws InvalidKeyException, NoSuchAlgorithmException, Nosuchproviderexc
			Eption, Signatureexception {try {x509name DN = new X509name (subject);
			Keypairgenerator KeyGen = keypairgenerator.getinstance ("RSA");
			Keygen.initialize (1024);
			KeyPair KP = Keygen.generatekeypair ();
			PKCS10CSR P10 = new PKCS10CSR ("Sha1withrsa", DN, Kp.getpublic (), New Derset (), kp.getprivate ());
			Pkcs10certificationrequest P10 = new//Pkcs10certificationrequest ("Sha1withrsa", DN, Kp.getpublic (),//NULL,
			Kp.getprivate ()); Pkcs10certificationrequest P10 = new//Pkcs10certificationrequest ("Sha1withrsa", DN, Kp.getpublic (), New//DERS
			ET (),//Kp.getprivate ());
			byte[] der = p10.getencoded ();
			String code = "-----BEGIN certificate REQUEST-----\ n";
			Code + = new String (Base64.encode (der));
			Code = "\-----End Certificate REQUEST-----\ n"; Certificationrequestinfo csrinfo = P10. getcertificationrequestInfo ();

			Savepem (Kp.getprivate (), Pempassword, Pempath);
		return code;
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
	return null; public static void Savex509certificate (X509Certificate certificate, String Cacertpath) throws Exception {Fileout
		Putstream stream = new FileOutputStream (Cacertpath);
		Stream.Write (certificate.getencoded ());
	Stream.Close (); public static void Savepem (Privatekey key, String Pempassword, String pempath) throws Exception {Pemwriter Write
		R = new Pemwriter (new FileWriter (Pempath));
		Writer.writeobject (Key, "DES-EDE3-CBC", Pempassword.tochararray (), New SecureRandom ());
	Writer.close ();  public static KeyPair Getprivatekey (String pempath, final string pempassword) throws Exception {Pemreader reader = new Pemreader (new InputStreamReader (New FileInputStream (Pempath)), new Passwordfinder () {public char[] Getpass Word () {//TODO auto-generated method stub RetuRN Pempassword.tochararray ();
		}
		});
		KeyPair key = (KeyPair) reader.readobject ();
	Return key; public static X509Certificate getcertificate (String cacertpath) throws Exception {Certificatefactory factory = n
		EW certificatefactory ();
		FileInputStream InputStream = new FileInputStream (Cacertpath);
		X509Certificate certificate = (x509certificate) factory. Enginegeneratecertificate (InputStream);
	return certificate; Public byte[] Createrootcert (string dn, string snstr, int validate, String cacertpath, String Capempath, String CaP
		Empassword) throws Exception {Keypairgenerator KeyGen = keypairgenerator.getinstance ("RSA");
		Keygen.initialize (2048);
		KeyPair KP = Keygen.generatekeypair ();
		X509v3certificategenerator Certgen = new X509v3certificategenerator ();
		Certgen.setserialnumber (New BigInteger (SNSTR));
		Certgen.setnotbefore (New Date (System.currenttimemillis ())); Certgen.setnotafter (New Date (System.currenttimemillis () + Validate * 24 * 60 ** 1000L));
		Certgen.setsubjectdn (New X500principal (DN));
		Certgen.setpublickey (Kp.getpublic ());
		Certgen.setissuerdn (New X500principal (DN));
		Certgen.setsignaturealgorithm ("Sha1withrsa");
		X509Certificate certificate = certgen.generate (Kp.getprivate ());
		Savex509certificate (certificate, Cacertpath);
		Savepem (Kp.getprivate (), Capempassword, Capempath);
	return certificate.getencoded (); @SuppressWarnings ("deprecation") public int Createusercert (string dn, string serialnumber, int validate, string us

		Ercertpath, String Userpempath, String Userpempassword, String Cacertpath, String Capempath, String Capempassword) {
			try {keypairgenerator keyGen = keypairgenerator.getinstance ("RSA");
			Keygen.initialize (1024);

			KeyPair KeyPair = Keygen.generatekeypair ();

			X509Certificate CACert = getcertificate (Cacertpath);

			KeyPair cakey = Getprivatekey (Capempath, Capempassword);
			X509v3certificategenerator Certgen = new X509v3certificategenerator (); X500principaL subjectname = new X500principal (DN);
			Certgen.setserialnumber (New BigInteger (serialnumber));
			Certgen.setissuerdn (Cacert.getsubjectx500principal ());
			Certgen.setnotbefore (New Date (System.currenttimemillis ()));
			Certgen.setnotafter (New Date (System.currenttimemillis () + Validate * * 1000L));
			Certgen.setsubjectdn (Subjectname);
			Certgen.setpublickey (Keypair.getpublic ());

			Certgen.setsignaturealgorithm ("Sha1withrsa");

			Certgen.addextension (X509extensions.authoritykeyidentifier, False, new Authoritykeyidentifierstructure (CaCert)); Certgen.addextension (X509extensions.subjectkeyidentifier, False, new Subjectkeyidentifierstructure (

			Keypair.getpublic ()));
			X509Certificate cert = certgen.generate (Cakey.getprivate (), "BC");
			Savex509certificate (cert, Usercertpath);
		Savepem (Keypair.getprivate (), Userpempassword, Userpempath);
		catch (Certificateparsingexception e) {//TODO auto-generated catch block E.printstacktrace (); Catch(InvalidKeyException e)
		{//TODO auto-generated catch block E.printstacktrace ();
		catch (Certificateencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (IllegalStateException e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Nosuchproviderexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (NoSuchAlgorithmException e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Signatureexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
	return 0; public static X509Certificate Signcert (String csrstr, String Usercertpath, String Cacertpath, String Capempath, Str ing Capempassword) throws InvalidKeyException, NoSuchAlgorithmException, Nosuchproviderexception, SignatureException , IOException, Operatorcreationexception, Certificateexception {try {csrstr = Csrstr.replaceall ("-----BEGIN certificate REQUEST-----\ n", "");
			Csrstr = Csrstr.replaceall ("\ n-----End certificate REQUEST-----\ n", "");

			byte[] der = Base64.decode (CSRSTR);

			KeyPair Capair;

			Capair = Getprivatekey (Capempath, Capempassword);
			X509Certificate CACert = getcertificate (Cacertpath);
			X500principal subjectname = new//X500principal (P10.getsubject (). toString ());

			Pkcs10certificationrequest P10CSR = new Pkcs10certificationrequest (der);
			Algorithmidentifier sigalgid = new Defaultsignaturealgorithmidentifierfinder (). Find ("Sha1withrsa");

			Algorithmidentifier digalgid = new Defaultdigestalgorithmidentifierfinder (). Find (Sigalgid);

			Asymmetrickeyparameter foo = Privatekeyfactory.createkey (Capair. Getprivate (). getencoded ());
			Subjectpublickeyinfo pkinfo = P10csr.getsubjectpublickeyinfo ();
			rsakeyparameters RSA = (rsakeyparameters) publickeyfactory. CreateKey (Pkinfo); rSAPUblickeyspec Rsaspec = new Rsapublickeyspec (Rsa.getmodulus (), rsa.getexponent ());
			Keyfactory KF = Keyfactory.getinstance ("RSA");

			PublicKey rsapub = Kf.generatepublic (Rsaspec);
			Subjectpublickeyinfo keyInfo = new Subjectpublickeyinfo (Asn1sequence.getinstance (rsapub.getencoded ())); X509v3certificatebuilder mycertificategenerator = new X509v3certificatebuilder (New X500name (CaCert.getIssuerDN (). GE Tname ()), New BigInteger ("1"), new Date (System.currenttimemillis ()), new Date (System.currenttimemillis () + 30 *

			365 * * 1000), P10csr.getsubject (), keyInfo);

			Contentsigner Siggen = new Bcrsacontentsignerbuilder (Sigalgid, Digalgid). Build (foo);
			
			X509certificateholder holder = mycertificategenerator.build (Siggen);
		
			Certificate Eex509certificatestructure = Holder.toasn1structure ();

			Certificatefactory CF = new certificatefactory (); Read certificate InputStream is1 = new Bytearrayinputstream (eex509certificAtestructure.getencoded ());
			X509Certificate Thecert = (x509certificate) cf. enginegeneratecertificate (IS1);
			Is1.close ();
			Savex509certificate (Thecert, Usercertpath);
		return thecert;
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
	return null; @SuppressWarnings ("deprecation") public int Createusercertex (string p10csr, string serialnumber, int validate, STR ing Usercertpath, string cacertpath, String Capempath, String Capempassword) {try {P10CSR = P10csr.replaceall ("-
			----BEGIN Certificate REQUEST-----\ n "," ");
			P10CSR = P10csr.replaceall ("\ n-----End certificate REQUEST-----\ n", "");
			byte[] der = Base64.decode (P10CSR);
			Pkcs10certificationrequest P10 = new Pkcs10certificationrequest (der);

			X509Certificate CACert = getcertificate (Cacertpath);
			
			
			KeyPair cakey = Getprivatekey (Capempath, Capempassword);
			Subjectpublickeyinfo pkinfo = P10.getsubjectpublickeyinfo (); Rsakeyparameters RSA = (rsakeyparameters) publickeyfactory. CreateKey (Pkinfo);
			Rsapublickeyspec Rsaspec = new Rsapublickeyspec (Rsa.getmodulus (), rsa.getexponent ());
			Keyfactory KF = Keyfactory.getinstance ("RSA");
			

			PublicKey rsapub = Kf.generatepublic (Rsaspec);
			X509v3certificategenerator Certgen = new X509v3certificategenerator ();
			X500principal subjectname = new X500principal (P10.getsubject (). toString ());
			Certgen.setserialnumber (New BigInteger (serialnumber));
			Certgen.setissuerdn (Cacert.getsubjectx500principal ());
			Certgen.setnotbefore (New Date (System.currenttimemillis ()));
			Certgen.setnotafter (New Date (System.currenttimemillis () + Validate * * 1000L));
			Certgen.setsubjectdn (Subjectname);
			Certgen.setpublickey (P10.getsubjectpublickeyinfo (). Getpublickey (). getencoded ());

			Certgen.setsignaturealgorithm ("Sha1withrsa"); Certgen.addextension (X509extensions.authoritykeyidentifier, False, new Authoritykeyidentifierstructure (CaCert)); Certgen.addextension (X509extensions.subjectkeyidentifier, False, new Subjectkeyidentifierstructure (

			Rsapub.getencoded ()));
			X509Certificate cert = certgen.generate (Cakey.getprivate (), "BC");
		Savex509certificate (cert, Usercertpath);
		catch (Certificateparsingexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (InvalidKeyException e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Certificateencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (IllegalStateException e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Nosuchproviderexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (NoSuchAlgorithmException e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Signatureexception e) {//TODO auto-generated catch block E.printstacktrace (); catch (Exception e) {//TODO AuTo-generated Catch block E.printstacktrace ();
	return 0; }//public static void Createusercert (String subjectdn, String snstr,//int validate, String cacertpath, String Capem Path,//String Capempassword, String Usercertpath, String Userpempath,//String Userpenpassword) throws Exception {/
	/X509Certificate CA = GetCertificate (Cacertpath);
	Keypairgenerator KeyGen = keypairgenerator.getinstance ("RSA");
	Keygen.initialize (1024);
	KeyPair pair = Keygen.generatekeypair ();
	X509v1certificategenerator Certgen = new X509v1certificategenerator ();
	Certgen.setserialnumber (New BigInteger (SNSTR));
	Certgen.setnotbefore (New Date (System.currenttimemillis ()));
	Certgen.setnotafter (New Date (System.currenttimemillis () + Validate *//* * 1000L));
	Certgen.setsubjectdn (New X500principal (SUBJECTDN));
	Certgen.setpublickey (Pair.getpublic ());
	Certgen.setissuerdn (Ca.getissuerx500principal ()); Certgen.setsignaturealgorithm ("Sha1withrsa");
	X509Certificate certificate = certgen.generate (Pair.getprivate ());
	byte[] src = certificate.getencoded ();
	KeyPair key = Getprivatekey (Capempath, Capempassword);
	Byte[] B = honganutils.rsasign (Key.getprivate (), SRC);
	X509certimpl Newcert = new X509certimpl (SRC);
	X509certinfo info = (x509certinfo) newcert.get (newcert.getname () + "."
	+ Newcert.info);
	X509certimpl export = new X509certimpl (info);
	Export.sign (Key.getprivate (), "Sha1withrsa");
	Savepem (Pair.getprivate (), Userpenpassword, Userpempath);
	Deroutputstream stream = new Deroutputstream (new FileOutputStream (//Usercertpath));
	Stream.Write (export.getencoded ());
	Stream.Close ();  Public java.security.cert.Certificate Certtox509cert (x509certificate cert) {try {certificatefactory CF = new
			Certificatefactory ();
			InputStream is = new Bytearrayinputstream (cert.getencoded ());
			Collection coll = cf.enginegeneratecertificates (IS); Java.security.cert.CertificateJCRT = null; 
			Iterator it = Coll.iterator (); 
				if (It.hasnext ()) {jcrt = (java.security.cert.Certificate) it.next ();
			return JCRT;
		The catch (Certificateencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();
		catch (Certificateexception e) {//TODO auto-generated catch block E.printstacktrace ();
	return null; public int storeP12 (string cacertpath, String Certpath, String Pempath, String Pempassword, String P12path, String
		P12password) {KeyPair kp;
			try {kp = Getprivatekey (Pempath, Pempassword);
			X509Certificate CACert = getcertificate (Cacertpath);
			X509Certificate cert = getcertificate (Certpath);
			Java.security.cert.certificate[] chain = new JAVA.SECURITY.CERT.CERTIFICATE[2];
			Chain[0] = Certtox509cert (cert);
			CHAIN[1] = Certtox509cert (CACert);
			KeyStore KS = keystore.getinstance ("PKCS12", "BC");
			Ks.load (null, NULL); Ks.setkeyentry (Parsecertdn (Cert.getsubjectdn (). GetName (), "CN"), KP.GEtprivate (), NULL, chain);
			FileOutputStream fout = new FileOutputStream (P12path);
		Ks.store (Fout, P12password.tochararray ());
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
	return 0;
 public static void Main (string[] args) {//TODO auto-generated method stub}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.