Java以编程方式生成CSR

时间:2020-02-23 14:35:01  来源:igfitidea点击:

最近,我不得不编写一个程序来使用Java API生成证书签名请求(CSR)。
其中我提供了Java程序生成CSR所遵循的步骤。
之后,我们还可以使用VeriSign CSR验证工具对它进行验证,以确保它是有效的。

在Java中以编程方式生成CSR的步骤

  • 使用标准加密算法获取KeyPairGenerator的实例。
    我在这里使用RSA。

  • 通过提供密钥大小和随机性来源来初始化实例。

  • 生成将在生成CSR中使用的PrivateKey和PublicKey。

  • 使用PublicKey初始化PKCS10。

  • 使用标准算法获取签名实例。
    我正在使用MD5WithRSA。

  • 使用PrivateKey初始化签名对象。

  • 通过传递通用名称,组织单位,组织,位置,州和国家/地区来创建X500Name对象

  • 使用X500Signer,Signature和X500Name对象对PKCS10对象进行编码和签名

  • 将PKCS10对象打印到PrintStream。
    之后,您可以将其保存在文件中或者在控制台中打印

Java程序生成CSR

这是执行上述所有步骤并生成CSR的Java程序。

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 [email protected]
 * @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", "theitroad", "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("theitroad.local <https://www.theitroad.local>");
		System.out.println("CSR Request Generated!!");
		System.out.println(csr);
	}

}

上面程序的输出是:

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

验证企业社会责任

获得CSR后,我们可以使用任何CSR Validator在线实用程序对其进行验证。