JAVA中将PrivateKey和X509Certificate对象保存为OpenSSL等程序可用的标准格式

我将两个个对象存进了ca.cert中,第一个是CA的私钥,第二个是CA的证书。

现在需要将ca.cert中的CA私钥和证书读取出来,并保存为OpenSSL等程序可识别的标准格式。

以下是代码:

import java.io.*;
import java.security.*;
import java.security.spec.*;
import java.security.cert.X509Certificate;
import java.util.*;
import sun.misc.BASE64Encoder;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure;

public class ExportKeys
{
	public static void main(String args[])
	{
		X509Certificate caCert = null;
    PrivateKey caPriKey = null;
    PublicKey caPubKey = null;
    
    BASE64Encoder encoder = null;
		
		try
		{
			FileInputStream caCertFis = new FileInputStream("ca.cert");
			ObjectInputStream caCertOis = new ObjectInputStream(caCertFis);
			caPriKey = (PrivateKey) caCertOis.readObject();
			caCert = (X509Certificate) caCertOis.readObject();
			caPubKey = caCert.getPublicKey();
			
			caCertOis.close();
			caCertFis.close();
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}
		
		//导出私钥
		try
		{
			encoder=new BASE64Encoder();
			String encoded=encoder.encode(caPriKey.getEncoded());
			FileWriter fw=new FileWriter("ca.key");
			fw.write("-----BEGIN PRIVATE KEY-----\n");
	    fw.write(encoded);
	    fw.write("\n");
	    fw.write("-----END PRIVATE KEY-----");
	    fw.close();
	  } catch (Exception ex)
		{
			ex.printStackTrace();
		}
		
		//导出证书
		try
		{
			encoder=new BASE64Encoder();
			String encoded=encoder.encode(caCert.getEncoded());
			FileWriter fw=new FileWriter("ca.crt");
			fw.write("-----BEGIN CERTIFICATE-----\n");
	    fw.write(encoded);
	    fw.write("\n");
	    fw.write("-----BEGIN CERTIFICATE-----");
	    fw.close();
	  } catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}
}

程序需要使用bouncycastle库来操作X509证书(即CA证书),下载地址在这里

编译命令和执行命令是:

编译:

javac -cp .;bcprov-ext-jdk15-145.jar ExportKeys.java

执行:

java -cp .;bcprov-ext-jdk15-145.jar ExportKeys

就是这样,完毕。

2 comments

  1. 品牌购 says:

    这个可以看看 博客很给力!

Leave a comment