证书构建
基于 bouncycastle
构建证书
# 导入依赖
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
<version>1.78.1</version>
</dependency>
# 代码
::: detail 示例代码
@Slf4j
@SuppressWarnings("unused")
public class CertificateGenerator {
static {
Security.addProvider(new BouncyCastleProvider());
}
@SneakyThrows
public static String getCertContent(X509Certificate certificate){
return "-----BEGIN CERTIFICATE-----\n" +
Base64.encode(certificate.getEncoded()) + "\n" +
"-----BEGIN CERTIFICATE-----\n";
}
/**
* 得到Cert内容
* @param certFile 证书文件
* @return Cert 字符
*/
public static String getCertContent(File certFile){
return FileUtil.readString(certFile, StandardCharsets.UTF_8);
}
/**
* 加载证书
* @param file file
* @return X509Certificate X509Certificate
*/
public static X509Certificate loadCertificate(File file) throws Exception{
try (FileInputStream fileInputStream = new FileInputStream(file)) {
return loadCertificate(fileInputStream);
}
}
/**
* 加载证书
* @param in 文件输入流
* @return X509Certificate X509Certificate
*/
public static X509Certificate loadCertificate(InputStream in) throws Exception{
Security.addProvider(new BouncyCastleProvider());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509","BC");
return (X509Certificate)certFactory.generateCertificate(in);
}
/**
* 加载证书
* @param text 证书字符
* @return X509Certificate X509Certificate
*/
public static X509Certificate loadCertificate(String text) throws Exception {
return loadCertificate(text,true);
}
/**
* 得到证书公钥
* @param certFile 证书文件
* @return X509Certificate X509Certificate
*/
public static PublicKey getCertificate(File certFile) throws Exception{
X509Certificate x509Certificate = loadCertificate(certFile);
return x509Certificate.getPublicKey();
}
/**
* 得到证书公钥
* @param cert 证书字符
* @return X509Certificate X509Certificate
*/
public static PublicKey getCertificate(String cert) throws Exception {
X509Certificate x509Certificate = loadCertificate(cert);
return x509Certificate.getPublicKey();
}
/**
* 加载证书
* @param text 证书字符
* @param includeHead 是否包括头
* @return X509Certificate X509Certificate
*/
public static X509Certificate loadCertificate(String text, boolean includeHead) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (includeHead){
bos.write(text.getBytes());
}else {
bos.write(Base64.decode(text));
}
InputStream myInputStream = new ByteArrayInputStream(bos.toByteArray());
return loadCertificate(myInputStream);
}
/**
* 得到Csr内容
* @param keyPair 密钥对
* @param subject X500Name 示例
* @return Csr 字符
*/
@SneakyThrows
public static String getCsrContent(KeyPair keyPair , X500Name subject){
// 将 CSR 导出为 PEM 格式
try (ByteArrayOutputStream csr = getCsr(keyPair, subject)) {
byte[] byteArray = csr.toByteArray();
return new String(byteArray, StandardCharsets.UTF_8);
}
}
/**
* 写入到文件
* @param path 写入文件路径
* @param keyPair 密钥对
* @param subject X500Name 实例
*/
@SneakyThrows
public static void writeToFile(String path,KeyPair keyPair ,X500Name subject){
// 将 CSR 导出为 PEM 格式
try (ByteArrayOutputStream csr = getCsr(keyPair, subject);
FileOutputStream fileOutputStream = new FileOutputStream(path)
) {
fileOutputStream.write(csr.toByteArray());
log.info("文件保存成功{} ", path);
}
}
/**
* 得到Csr
* @param subject 使用人
*/
@SneakyThrows
private static ByteArrayOutputStream getCsr(KeyPair keyPair ,X500Name subject){
PKCS10CertificationRequest csr = getPkcs10CertificationRequest(keyPair, subject, keyPair.getPublic());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try (
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(stream);
PemWriter pemWriter = new PemWriter(outputStreamWriter);
) {
pemWriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded()));
}
return stream;
}
/**
* 获取PKCS 10认证请求
* @param keyPair 密钥对
* @param subject X500Name
* @param publicKey 公钥
* @return PKCS10CertificationRequest
* @throws OperatorCreationException 创建异常
*/
private static PKCS10CertificationRequest getPkcs10CertificationRequest(KeyPair keyPair, X500Name subject, PublicKey publicKey) throws OperatorCreationException {
//构建CSR
JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(subject, publicKey);
//签名 CSR
ContentSigner contentSigner = new JcaContentSignerBuilder("SM3withSM2")
.setProvider("BC").build(keyPair.getPrivate());
return csrBuilder.build(contentSigner);
}
/**
* 得到一组密钥对
* @return SM2 密钥对
*/
@SneakyThrows
public static KeyPair getKeyPair() {
// 生成SM2密钥对
// 获取一个椭圆曲线类型的密钥对生成器
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
// 使用SM2参数初始化生成器
keyPairGenerator.initialize(ECNamedCurveTable.getParameterSpec("sm2p256v1"), new SecureRandom());
//得到秘钥对
return keyPairGenerator.generateKeyPair();
}
/**
* 获取私钥(16进制字符串,头部不带00长度共64)
* @param privateKey 私钥
* @return 私钥内容
*/
public static String getPriKeyHexString(PrivateKey privateKey){
//只获取私钥里的d,32字节
BCECPrivateKey s=(BCECPrivateKey)privateKey;
String priKeyHexString = Hex.toHexString(s.getD().toByteArray());
// if(priKeyHexString.length() == 66 && "00".equals(priKeyHexString.substring(0, 2))){
// return priKeyHexString.substring(2);
// }
return priKeyHexString;
}
/**
* 获取公钥(16进制字符串,头部带04长度共130)
* @param publicKey 公钥
* @return 公钥内容
*/
public static String getPubKeyHexString(PublicKey publicKey){
BCECPublicKey p=(BCECPublicKey)publicKey;
String pubKeyHexString = Hex.toHexString(p.getQ().getEncoded(false));
if(pubKeyHexString.length() == 130 && pubKeyHexString.startsWith("04")){
return pubKeyHexString.substring(2);
}
return pubKeyHexString;
}
}
上次更新: 2024/11/05, 08:29:31