import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBMPString;
import org.bouncycastle.asn1.DERInputStream;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.provider.JDKPKCS12KeyStore;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure;
import org.springframework.core.io.Resource;
import steel.share.clientcert.ClientCert;
public class ClientCertGenerator {
private Resource rootCertFilePath;
private Resource rootKeyFilePath;
private int serialNumber;
public void genClientCert(ClientCert clientCert, OutputStream fileOutputStream) {
try {
X509Certificate rootCert = loadRootCertificate();
PrivateKey rootPrivateKey = loadRootPrivateKeyByKeyFile();
KeyPair clientKeyPair = genClientKeyPair();
X509Certificate signedCert = signCert(rootCert.getPublicKey(), rootPrivateKey, rootCert, clientKeyPair,
clientCert);
PKCS12BagAttributeCarrier bagAttributeCarrier = (PKCS12BagAttributeCarrier) signedCert;
bagAttributeCarrier.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(
clientCert.getCommonName() + "'s key"));
bagAttributeCarrier.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
new SubjectKeyIdentifierStructure(clientKeyPair.getPublic()));
Certificate[] certChain = new Certificate[1];
certChain[0] = signedCert;
JDKPKCS12KeyStore ks = new JDKPKCS12KeyStore.BCPKCS12KeyStore();
ks.engineSetKeyEntry(clientCert.getCommonName(), clientKeyPair.getPrivate(), clientCert.getPassword()
.toCharArray(), certChain);
ks.engineStore(fileOutputStream, clientCert.getPassword().toCharArray());
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private X509Certificate loadRootCertificate() {
InputStream certIn = null;
try {
CertificateFactory fac = CertificateFactory.getInstance("X.509");
return (X509Certificate) fac.generateCertificate(rootCertFilePath.getInputStream());
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (certIn != null) {
try {
certIn.close();
} catch (IOException ie) {
}
}
}
}
private PrivateKey loadRootPrivateKeyByKeyFile() {
BufferedInputStream privateIn = null;
ByteArrayOutputStream privateByteOut = null;
try {
privateIn = (BufferedInputStream) rootKeyFilePath.getInputStream();
privateByteOut = new ByteArrayOutputStream();
int len = 0;
while ((len = privateIn.read()) != -1) {
privateByteOut.write(len);
}
byte[] privateBytes = privateByteOut.toByteArray();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey rootPrivateKey = keyFactory.generatePrivate(keySpec);
return rootPrivateKey;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (privateIn != null) {
try {
privateIn.close();
} catch (IOException ie) {
}
}
if (privateByteOut != null) {
try {
privateByteOut.close();
} catch (IOException ie) {
}
}
}
}
private KeyPair genClientKeyPair() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
return generator.generateKeyPair();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@SuppressWarnings("unchecked")
private X509Certificate signCert(PublicKey rootPublicKey, PrivateKey rootPrivateKey, X509Certificate certificate,
KeyPair clientKeyPair, ClientCert clientCert) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Hashtable attrs = new Hashtable();
Vector order = new Vector();
attrs.put(X509Principal.C, clientCert.getCountryCode());
attrs.put(X509Principal.O, clientCert.getOrganizationCode());
attrs.put(X509Principal.OU, clientCert.getOrganizationalName());
attrs.put(X509Principal.CN, clientCert.getCommonName());
attrs.put(X509Principal.L, clientCert.getCityName());
attrs.put(X509Principal.ST, clientCert.getProvinceName());
order.addElement(X509Principal.CN);
order.addElement(X509Principal.OU);
order.addElement(X509Principal.O);
order.addElement(X509Principal.L);
order.addElement(X509Principal.ST);
order.addElement(X509Principal.C);
X509V3CertificateGenerator _v3CertGenerator = new X509V3CertificateGenerator();
_v3CertGenerator.reset();
Date beginDate = new Date();
_v3CertGenerator.setSerialNumber(BigInteger.valueOf(serialNumber));
_v3CertGenerator.setIssuerDN(certificate.getIssuerX500Principal());
_v3CertGenerator.setNotBefore(new Date());
_v3CertGenerator.setNotAfter(new Date(beginDate.getTime() + 730 * 24 * 60 * 60 * 1000L));
_v3CertGenerator.setSubjectDN(new X509Principal(order, attrs));
_v3CertGenerator.setPublicKey(clientKeyPair.getPublic());
_v3CertGenerator.setSignatureAlgorithm("SHA1withRSA");
_v3CertGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
createSubjectKeyIdentifier(clientKeyPair.getPublic()));
_v3CertGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
createAuthorityKeyIdentifier(rootPublicKey));
_v3CertGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
X509Certificate cert = _v3CertGenerator.generate(rootPrivateKey, "BC");
cert.checkValidity(new Date());
cert.verify(rootPublicKey);
return cert;
}
@SuppressWarnings("deprecation")
public AuthorityKeyIdentifier createAuthorityKeyIdentifier(PublicKey rootPublicKey) {
try {
ByteArrayInputStream bIn = new ByteArrayInputStream(rootPublicKey.getEncoded());
SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(bIn).readObject());
return new AuthorityKeyIdentifier(info);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@SuppressWarnings("deprecation")
public SubjectKeyIdentifier createSubjectKeyIdentifier(PublicKey clientPublicKey) {
try {
ByteArrayInputStream bIn = new ByteArrayInputStream(clientPublicKey.getEncoded());
SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(bIn).readObject());
return new SubjectKeyIdentifier(info);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public Resource getRootCertFilePath() {
return rootCertFilePath;
}
public void setRootCertFilePath(Resource rootCertFilePath) {
this.rootCertFilePath = rootCertFilePath;
}
public Resource getRootKeyFilePath() {
return rootKeyFilePath;
}
public void setRootKeyFilePath(Resource rootKeyFilePath) {
this.rootKeyFilePath = rootKeyFilePath;
}
public int getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(int serialNumber) {
this.serialNumber = serialNumber;
}
}
分享到:
相关推荐
Java生成证书工具类
Java 生成证书包括 OpenSSL Java 生成证书是指通过 Java 的 keytool 工具和 OpenSSL 库生成数字证书的过程。在 HTTPS 环境下,证书是必不可少的组件, play a crucial role in ensuring the security and ...
java生成https安全证书,解决httpClient访问https出错 编译:javac InstallCert.java 运行:java InstallCert 要访问的网址 结果:Enter certificate to add to trusted keystore or 'q' to quit: [1] 输入1确认生成...
Java 生成数字签名,数字证书的实现代码,得到RSA密钥对,产生Signature对象,对用私钥对信息(info)签名.Signature mySig = Signature.getInstance("SHA1WithRSA"); //用指定算法产生签名对象 mySig.initSign...
标题“certificate-generator-master_java证书生成_”暗示我们关注的是一个用于生成证书的Java项目,而描述“java 生成证书”进一步确认了这一点。我们将探讨Java中生成证书的基本概念、工具和步骤。 在Java中,...
然而,本案例中我们不使用keytool,而是通过编程方式生成证书。 4. **Java密钥和证书管理**:在Java中,`java.security.KeyPairGenerator`类用于生成密钥对,`java.security.cert.Certificate`接口代表证书,而`...
Java生成CA证书涉及到了几个关键概念,包括公钥加密、私钥解密、数字签名以及证书颁发机构(CA)。在Java中,我们可以使用内置的Java Cryptography Extension (JCE)库来实现这些功能。以下是对这个主题的详细阐述: ...
工具内容有完整的CSR生成及对应秘钥保存,使用java.securtiy Signature类
java批量生成证书,通过用java文件生成bat,避免一各个敲命令的苦力方式.
在Java编程环境中,生成数字证书是一项关键的安全技术,主要用于数据加密、身份验证和签名等应用场景。数字证书通常包含了公钥和私钥对,以及证书持有者的相关信息,这些信息经过认证机构(CA)的签名,确保了证书的...
Java 生成证书 在 Java 中,可以使用 KeyTool 工具来生成数字证书。KeyTool 是一个命令行工具,用于生成和管理数字证书。使用 KeyTool 可以生成自签名证书、私钥证书、CSR 证书等。 Java 解析证书 在 Java 中,可以...
Java调用OpenSSL生成证书是一种常见的安全操作,用于创建数字证书,这些证书在网络安全中扮演着重要角色,例如HTTPS通信、服务器身份验证等。在这个过程中,我们通常会使用OpenSSL命令行工具,然后通过Java程序来...
国密算法是我国自主研发创新的一套数据加密处理系列算法,很多项目都在用了,所以用Java代码生成的基于国密算法签发的sm2 证书,放到资源里面方便大家下载使用。
Java生成PDF文件是一种常见的技术需求,特别是在开发报告生成、电子发票、文档自动化等领域。PDF(Portable Document Format)格式因其跨平台、保持原始样式的特点而被广泛使用。在Java环境中,有多个库可以帮助...
Java实现RSA加密解密,数字证书生成与验证,模拟两个端通信,AB双方通信,客户端A把需要传输的文件MD5值用自己的私钥生成数字签名,连同明文用服务端B的公钥加密后传送给服务端B,服务端B用私钥解密验证数字签名,并计算...
在这个场景中,我们不仅会讨论如何使用Java生成X509证书,还会涉及如何将其存储为PEM格式,以及如何将整个流程封装到一个jar包中。 首先,我们需要了解X509证书的基本结构。X509证书包含了主体信息(如组织名、组织...
使用java生成证书及其openssl获取公私钥 使用java生成yangjie.jks证书, 即生成公私钥密码对 keytool -genkeypair -alias yangjie -keyalg RSA -keypass yangjie -keystore yangjie.jks -storepass yangjie keytool...
总结来说,Java生成及验证Android签名文件涉及到的关键知识点有: 1. Java Key Store (JKS):存储密钥和证书的安全容器。 2. `keytool`:JDK自带的命令行工具,用于管理和生成keystore。 3. 密钥对:包括公钥和私钥...