使用java代码实现签发服务器通信证书
时间: 2023-05-21 18:02:42 浏览: 133
java一机一密实现代码
可以使用Java的KeyStore类来生成和管理证书。以下是一个简单的示例代码:
```
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.security.auth.x500.X500Principal;
import sun.security.x509.*;
public class CertificateGenerator {
public static void main(String[] args) throws Exception {
// Generate a key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Generate a self-signed X.509 certificate
X500Name issuer = new X500Name("CN=My Company, O=My Organization, L=My City, ST=My State, C=My Country");
X500Name subject = issuer;
Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); // Yesterday
Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); // One year from now
BigInteger serialNumber = new BigInteger(64, new SecureRandom());
X509CertInfo certInfo = new X509CertInfo();
certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(serialNumber));
certInfo.set(X509CertInfo.SUBJECT, new CertificateSubjectName(subject));
certInfo.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer));
certInfo.set(X509CertInfo.VALIDITY, new CertificateValidity(startDate, endDate));
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid)));
X509CertImpl cert = new X509CertImpl(certInfo);
cert.sign(keyPair.getPrivate(), "SHA256withRSA");
// Save the certificate to a file
FileOutputStream fos = new FileOutputStream("server.crt");
fos.write(cert.getEncoded());
fos.close();
// Save the private key to a file
fos = new FileOutputStream("server.key");
fos.write(keyPair.getPrivate().getEncoded());
fos.close();
}
}
```
这个示例代码生成一个2048位的RSA密钥对,并使用SHA256withRSA签名算法生成一个自签名的X.509证书。证书的有效期为一年,保存在server.crt文件中,私钥保存在server.key文件中。
阅读全文