java生成pfx_JAVA代码-数字证书公私钥生成-公钥cer ,私钥jks, pfx格式

java生成pfx_JAVA代码-数字证书公私钥生成-公钥cer ,私钥jks, pfx格式importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.FileWriter;importjava.io.IOException;importjava.math.BigInteger;importjava.security.InvalidKeyException;im…

大家好,又见面了,我是你们的朋友全栈君。

importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.FileWriter;importjava.io.IOException;importjava.math.BigInteger;importjava.security.InvalidKeyException;importjava.security.Key;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.KeyStore;importjava.security.KeyStoreException;importjava.security.NoSuchAlgorithmException;importjava.security.NoSuchProviderException;importjava.security.SecureRandom;importjava.security.Security;importjava.security.SignatureException;importjava.security.cert.CertificateEncodingException;importjava.security.cert.CertificateException;importjava.security.cert.CertificateFactory;importjava.security.cert.X509Certificate;importjava.util.Date;importjava.util.Enumeration;importorg.bouncycastle.asn1.x509.X509Name;importorg.bouncycastle.jce.X509V3CertificateGenerator;importorg.bouncycastle.jce.provider.BouncyCastleProvider;importsun.misc.BASE64Encoder;public classDataCertCreate {private String path = “D:/”;/*** 公钥方法*/

static{

Security.addProvider(newBouncyCastleProvider());

}/*** 产生数字公钥证书 String[]

* info长度为9,分别是{cn,ou,o,c,l,st,starttime,endtime,serialnumber}

*

*@throwsSignatureException

*@throwsSecurityException

*@throwsNoSuchProviderException

*@throwsInvalidKeyException*/

publicX509Certificate generateCert(String[] info, KeyPair keyPair_root, KeyPair keyPair_user)throwsInvalidKeyException, NoSuchProviderException, SecurityException, SignatureException {

X509V3CertificateGenerator certGen= newX509V3CertificateGenerator();

X509Certificate cert= null;

certGen.setSerialNumber(new BigInteger(info[8]));

certGen.setIssuerDN(new X509Name(“CN=huahua, OU=hnu, O=university , C=china”));

certGen.setNotBefore(new Date(Long.parseLong(info[6])));

certGen.setNotAfter(new Date(Long.parseLong(info[7])));

certGen.setSubjectDN(new X509Name(“C=” + info[0] + “,OU=” + info[1] + “,O=” + info[2] + “,C=” + info[3] + “,L=”

+ info[4] + “,ST=” + info[3]));

certGen.setPublicKey(keyPair_user.getPublic());

certGen.setSignatureAlgorithm(“SHA1WithRSA”);

cert= certGen.generateX509Certificate(keyPair_root.getPrivate(), “BC”);returncert;

}/*** 私钥方法*/

private String KEYSTORE_PASSWORD = “2078888”;/*** 创建空的jks文件 String[]

* info长度为9,分别是{cn,ou,o,c,l,st,starttime,endtime,serialnumber}*/

public voidgenerateJKS(String[] info) {try{

KeyStore keyStore= KeyStore.getInstance(“jks”);

keyStore.load(null, null);

keyStore.store(new FileOutputStream(“D:/” + info[0] + “.jks”), KEYSTORE_PASSWORD.toCharArray());

}catch (KeyStoreException | NoSuchAlgorithmException | CertificateException |IOException e) {

e.printStackTrace();

}

}/*** 使用空的jks创建自己的jks String[]

* info长度为9,分别是{cn,ou,o,c,l,st,starttime,endtime,serialnumber}*/

public voidstoreJKS(String[] info, KeyPair keyPair_root, KeyPair keyPair_user) {

KeyStore keyStore;try{//use exited jks file

keyStore = KeyStore.getInstance(“JKS”);

keyStore.load(new FileInputStream(“D:/” + info[0] + “.jks”), KEYSTORE_PASSWORD.toCharArray());//generate user’s keystore by info[8] —–keypair

X509V3CertificateGenerator certGen = newX509V3CertificateGenerator();

certGen.setSerialNumber(new BigInteger(info[8]));

certGen.setIssuerDN(new X509Name(“CN=huahua, OU=hnu, O=university , C=china”));

certGen.setNotBefore(new Date(Long.parseLong(info[6])));

certGen.setNotAfter(new Date(Long.parseLong(info[7])));

certGen.setSubjectDN(new X509Name(“C=” + info[0] + “,OU=” + info[1] + “,O=” + info[2] + “,C=” + info[3]+ “,L=” + info[4] + “,ST=” + info[3]));

certGen.setPublicKey(keyPair_user.getPublic());

certGen.setSignatureAlgorithm(“SHA1WithRSA”);

X509Certificate cert= null;

Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());

cert= certGen.generateX509Certificate(keyPair_root.getPrivate(), “BC”);

X509Certificate[] chain= new X509Certificate[1];

chain[0] =cert;

keyStore.setKeyEntry(“mykey”, keyPair_user.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), chain);

keyStore.setCertificateEntry(“single_cert”, cert);

keyStore.store(new FileOutputStream(“D:/” + info[0] + “.jks”), KEYSTORE_PASSWORD.toCharArray());

}catch(Exception e) {

e.printStackTrace();

}

}/*** 公私钥公共方法*/

/*** 根据seed产生密钥对

*

*@paramseed

*@return*@throwsNoSuchAlgorithmException*/

public KeyPair generateKeyPair(int seed) throwsNoSuchAlgorithmException {

KeyPairGenerator kpg= KeyPairGenerator.getInstance(“RSA”);

kpg.initialize(1024, new SecureRandom(new byte[seed]));

KeyPair keyPair=kpg.generateKeyPair();returnkeyPair;

}public static final String PKCS12 = “PKCS12”;/*** 转换成pfx格式

*

*@paraminfo*/

publicBoolean toPFX(String[] info) {try{

String pfx_keystore_file= “D:/” + info[0] + “.pfx”;

String jkx_keystore_file= “D:/” + info[0] + “.jks”;

KeyStore inputKeyStore= KeyStore.getInstance(“JKS”);

FileInputStream fis= newFileInputStream(jkx_keystore_file);char[] nPassword = null;if ((KEYSTORE_PASSWORD == null) || KEYSTORE_PASSWORD.trim().equals(“”)) {

nPassword= null;

}else{

nPassword=KEYSTORE_PASSWORD.toCharArray();

}

inputKeyStore.load(fis, nPassword);

fis.close();

KeyStore outputKeyStore= KeyStore.getInstance(“PKCS12”);

outputKeyStore.load(null, KEYSTORE_PASSWORD.toCharArray());

Enumeration enums=inputKeyStore.aliases();while(enums.hasMoreElements()) {

String keyAlias=(String) enums.nextElement();

System.out.println(“alias=[” + keyAlias + “]”);if(inputKeyStore.isKeyEntry(keyAlias)) {

Key key=inputKeyStore.getKey(keyAlias, nPassword);

java.security.cert.Certificate[] certChain=inputKeyStore.getCertificateChain(keyAlias);

outputKeyStore.setKeyEntry(keyAlias, key, KEYSTORE_PASSWORD.toCharArray(), certChain);

}

}

FileOutputStream out= newFileOutputStream(pfx_keystore_file);

outputKeyStore.store(out, nPassword);

out.close();return true;

}catch(Exception e) {

e.printStackTrace();

System.out.println(“toPFX :” +e.getMessage());return false;

}

}public booleancreatePublicKey(String[] info) {try{

KeyPair keyPair_root= generateKeyPair(10);

KeyPair keyPair_user= generateKeyPair(100);

X509Certificate cert=generateCert(info, keyPair_root, keyPair_user);

String certPath= path + info[0] + “.cer”;

FileOutputStream fos= newFileOutputStream(certPath);

BASE64Encoder encoder= newBASE64Encoder();

String string=encoder.encode(cert.getEncoded());

System.out.println(string);

fos.write(cert.getEncoded());

fos.close();return true;

}catch(Exception e) {

e.printStackTrace();

System.out.println(“public key :” +e.getMessage());return false;

}

}public booleancreatePublicKeyBYDecode(String[] info) {try{

KeyPair keyPair_root= generateKeyPair(10);

KeyPair keyPair_user= generateKeyPair(100);

X509Certificate cert=generateCert(info, keyPair_root, keyPair_user);

String certPath= path + info[0] + “_base.cer”;

FileWriter wr= new java.io.FileWriter(newFile(certPath));

String encode= newBASE64Encoder().encode(cert.getEncoded());

String strCertificate= “—–BEGIN CERTIFICATE—–\r\n” + encode + “\r\n—–END CERTIFICATE—–\r\n”;

wr.write(strCertificate);//给证书编码

wr.flush();

wr.close();return true;

}catch(Exception e) {

e.printStackTrace();

System.out.println(“public key :” +e.getMessage());return false;

}

}publicX509Certificate fromString(String cert) {try{

CertificateFactory certificateFactory= CertificateFactory.getInstance(“X.509”);

String strCertificate= “—–BEGIN CERTIFICATE—–\n” + cert + “\n—–END CERTIFICATE—–\n”;

java.io.ByteArrayInputStream streamCertificate= newjava.io.ByteArrayInputStream(

strCertificate.getBytes(“UTF-8”));return(X509Certificate) certificateFactory.generateCertificate(streamCertificate);

}catch(Exception ex) {

System.out.println(ex.getMessage());

}return null;

}public booleancreatePrivateKey(String[] info) {try{

KeyPair keyPair_root= generateKeyPair(10);

KeyPair keyPair_user= generateKeyPair(100);

generateJKS(info);

storeJKS(info, keyPair_root, keyPair_user);return true;

}catch(NoSuchAlgorithmException e) {

e.printStackTrace();

System.out.println(“private key :” +e.getMessage());return false;

}

}public static void main(String[] args) throwsNoSuchAlgorithmException, InvalidKeyException,

NoSuchProviderException, SecurityException, SignatureException, CertificateEncodingException, IOException {

DataCertCreate dataCertCreate= newDataCertCreate();

String[] info= { “huahua_user”, “hnu”, “university”, “china”, “hunan”, “changsha”, “111111”, “11111111”, “1”};//生成公钥

boolean createPublicKey =dataCertCreate.createPublicKey(info);

System.out.println(“PUBLIC KEY CREATE OK, result==” +createPublicKey);boolean createPublicKeyBYDecode =dataCertCreate.createPublicKeyBYDecode(info);

System.out.println(“PUBLIC KEY BY BASE64Encoder CREATE OK, result==” +createPublicKeyBYDecode);boolean createPrivateKey =dataCertCreate.createPrivateKey(info);

System.out.println(“PRIVATE KEY CREATE OK, result==” +createPrivateKey);

Boolean pfx=dataCertCreate.toPFX(info);

System.out.println(“transToPFX OK, result==” +pfx);

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/139701.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • webstorm2021.7激活码【中文破解版】

    (webstorm2021.7激活码)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.cn/100143.htmlMLZPB5EL5Q-eyJsa…

  • 【java系列】unix时间戳转Date[通俗易懂]

    【java系列】unix时间戳转Date[通俗易懂]unix时间戳转Date注意,不能直接使用Integer进行乘除和转换,需要转成bigDecimal去处理,否则转换出来的时间只会是1970-xxxxpackagehutoolTest;importcn.hutool.core.date.DateTime;importjava.math.BigDecimal;importjava.text.SimpleDateFormat;importjava.util.Date;publicclassDateTest{pub

  • Unity3d场景快速烘焙【2020】

    Unity3d场景快速烘焙【2020】很多刚刚接触Unity3d的童鞋花了大量的时间自学,可总是把握不好Unity3d的烘焙,刚从一个坑里爬出来,又陷入另一个新的坑,每次烘焙一个场景少则几个小时,多则几十个小时,机器总是处于假死机状态,半天看不到结果,好不容易烘焙完了,黑斑、撕裂、硬边、漏光或漏阴影等缺陷遍布,惨不忍睹,整体效果暗无层次,或者苍白无力,灯光该亮的亮不起来,该暗的暗不下去,更谈不上有什么意境,痛苦的折磨,近乎失去了信心,一个团队从建模到程序,都没什么问题,可一到烘焙这一关,就堵得心塞,怎么也搞不出好的视觉效果,作品没法及时向用户交

  • python 递归深度

    python 递归深度python对于递归深度有默认的设置,当递归层数过深,超过1000时,会报错RecursionError:maximumrecursiondepthexceededwhilecallingaPythonobject可以通过如下设置:importsyssys.setrecursionlimit(1200)手动设置递归深度,测试后发现,最大上限在8

  • HorizontalScrollView

    HorizontalScrollView一、概述、水平滚动条可以左右滑动可与ViewPager协同使用二、HorizontalScrollView里边只能放一个子元素可以放一个Layout布局对象来盛放多个元素里边可以设置指示器

  • 树莓派怎么安装pycharm_树莓派卸载python2.7

    树莓派怎么安装pycharm_树莓派卸载python2.71、下载pycharm通过VNC界面下载pycharm或者在其他系统下载后推送到树莓派,下载地址pycharm_linux2、将下载的文件复制到/opt文件夹如果在树莓派中直接下载的,会在’/home/pi/下载’文件夹,将下载的文件复制到/opt文件夹sudomvpycharm-community-2020.1.1.tar.gz/opt/pycharm-community-2020.1.1…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号