数字证书java代码实现
时间: 2024-06-15 18:06:13 浏览: 108
数字证书是一种用于验证身份和加密通信安全工具。在Java中,可以使用Java的密钥库(KeyStore)和相关类来实现数字证书的功能。下面是一个简单的示例代码,演示了如何生成数字证书和使用数字证书进行加密和解密:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import javax.crypto.Cipher;
public class DigitalCertificateExample {
public static void main(String[] args) throws Exception {
// 生成数字证书
generateCertificate();
// 使用数字证书进行加密和解密
encryptAndDecrypt();
}
public static void generateCertificate() throws Exception {
// 生成密钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 创建自签名证书
X509Certificate cert = generateSelfSignedCertificate(keyPair);
// 将证书保存到文件
FileOutputStream fos = new FileOutputStream("certificate.cer");
fos.write(cert.getEncoded());
fos.close();
}
public static X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws Exception {
// 创建证书生成工厂
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// 创建证书生成器
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(new X500Principal("CN=Self Signed Certificate"));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 365));
certGen.setSubjectDN(new X500Principal("CN=Self Signed Certificate"));
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSA");
// 生成证书
return certGen.generate(keyPair.getPrivate(), "BC");
}
public static void encryptAndDecrypt() throws Exception {
// 加载数字证书
FileInputStream fis = new FileInputStream("certificate.cer");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(fis);
PublicKey publicKey = cert.getPublicKey();
// 加密数据
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal("Hello, World!".getBytes());
// 解密数据
PrivateKey privateKey = keyPair.getPrivate();
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData = cipher.doFinal(encryptedData);
System.out.println("Decrypted Data: " + new String(decryptedData));
}
}
```
请注意,上述代码仅为示例,实际使用时可能需要根据具体需求进行修改和完善。
阅读全文