1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
| import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.*; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.cert.X509CRLHolder; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v2CRLBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.PKCS8Generator; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder; import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8EncryptorBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.InputDecryptorProvider; import org.bouncycastle.operator.OutputEncryptor; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfoBuilder; import org.bouncycastle.pkcs.jcajce.JcaPKCS8EncryptedPrivateKeyInfoBuilder; import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.RSAPrivateCrtKey; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECPublicKeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.Date;
@Slf4j public class CertUtil {
static { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } }
@Data public static class CaCertFileBytes { private byte[] keyFileBytes; private byte[] pemFileBytes; private byte[] derFileBytes; private X509Certificate caCertificate; }
@Data public static class ServerCertFileBytes { private byte[] keyFileBytes; private byte[] pemFileBytes; private byte[] crtFileBytes; private byte[] p12FileBytes; }
@Data public static class ClientCertFileBytes { private byte[] p12FileBytes; private String clientSerialNo; }
public enum CertAlgo { RSA, EC; }
public static KeyPair generatePrivateKey(CertAlgo algo) throws Exception { if (algo == CertAlgo.RSA) { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC"); keyPairGenerator.initialize(2048); return keyPairGenerator.generateKeyPair(); } else if (algo == CertAlgo.EC) { KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "BC"); kpg.initialize(new ECGenParameterSpec("secp256r1")); return kpg.generateKeyPair(); } else { throw new IllegalStateException("不支持的证书加密算法"); } }
public static byte[] getPrivateKeyToKeyFileBytes(KeyPair keyPair, String cipher) throws Exception { char[] password = cipher.toCharArray(); PKCS8EncryptedPrivateKeyInfoBuilder privateKeyBuilder = new JcaPKCS8EncryptedPrivateKeyInfoBuilder(keyPair.getPrivate()); OutputEncryptor encryptor = new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_3DES) .setProvider("BC") .setPasssword(password) .build(); PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = privateKeyBuilder.build(encryptor); StringWriter privateKeyStringWriter = new StringWriter();
try (JcaPEMWriter privateKeyPemWriter = new JcaPEMWriter(privateKeyStringWriter)) { privateKeyPemWriter.writeObject(encryptedPrivateKeyInfo); } return privateKeyStringWriter.toString().getBytes(); }
public static CaCertFileBytes generateCaFileBytes(CertAlgo algo, String cipher, BigInteger serialNum, X500Name x500Name, Date startDate, Date endDate, String crlDistributionPoints) throws Exception { CaCertFileBytes result = new CaCertFileBytes(); KeyPair keyPair = generatePrivateKey(algo);
byte[] keyFileBytes = getPrivateKeyToKeyFileBytes(keyPair, cipher); result.setKeyFileBytes(keyFileBytes);
X509CertificateHolder caHolder = getCaX509Holder(keyPair, serialNum, x500Name, x500Name, startDate, endDate, crlDistributionPoints); X509Certificate caCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(caHolder); result.setCaCertificate(caCert);
StringWriter certStringWriter = new StringWriter(); try (JcaPEMWriter pemWriter = new JcaPEMWriter(certStringWriter)) { pemWriter.writeObject(caCert); } result.setPemFileBytes(certStringWriter.toString().getBytes());
result.setDerFileBytes(caCert.getEncoded()); return result; }
public static ServerCertFileBytes generateServerFileBytes(CertAlgo algo, PrivateKey caPrivateKey, PublicKey caPublicKey, String friendlyName, String cipher, BigInteger serialNum, X500Name issuer, X500Name subject, Date startDate, Date endDate, String crlDistributionPoints) throws Exception { ServerCertFileBytes result = new ServerCertFileBytes();
KeyPair serverKeyPair = generatePrivateKey(algo); byte[] keyFileBytes = getPrivateKeyToKeyFileBytes(serverKeyPair, cipher); result.setKeyFileBytes(keyFileBytes);
X509Certificate serverCert = signAndGetCustomX509Certificate( true, serverKeyPair.getPublic(), caPrivateKey, caPublicKey, serialNum, issuer, subject, startDate, endDate, crlDistributionPoints );
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); JcaPEMWriter pemWriter = new JcaPEMWriter(new OutputStreamWriter(bos))) { pemWriter.writeObject(serverCert); pemWriter.flush(); byte[] certBytes = bos.toByteArray(); result.setCrtFileBytes(certBytes); result.setPemFileBytes(certBytes); }
byte[] p12FileBytes = getP12FileBytes(serverKeyPair, cipher, serverCert, friendlyName); result.setP12FileBytes(p12FileBytes); return result; }
public static ServerCertFileBytes generateServerFileBytes(CertAlgo algo, PrivateKey caPrivateKey, String friendlyName, String cipher, BigInteger serialNum, X500Name issuer, X500Name subject, Date startDate, Date endDate, String crlDistributionPoints) throws Exception { PublicKey caPublicKey = derivePublicKeyFromPrivateKey(caPrivateKey); return generateServerFileBytes(algo, caPrivateKey, caPublicKey, friendlyName, cipher, serialNum, issuer, subject, startDate, endDate, crlDistributionPoints); }
public static ServerCertFileBytes generateServerFileBytes(CertAlgo algo, PrivateKey caPrivateKey, X509Certificate caCert, String friendlyName, String cipher, BigInteger serialNum, X500Name issuer, X500Name subject, Date startDate, Date endDate, String crlDistributionPoints) throws Exception { return generateServerFileBytes(algo, caPrivateKey, caCert != null ? caCert.getPublicKey() : null, friendlyName, cipher, serialNum, issuer, subject, startDate, endDate, crlDistributionPoints); }
public static ClientCertFileBytes generateClientFileBytes(CertAlgo algo, PrivateKey caPrivateKey, PublicKey caPublicKey, String friendlyName, String cipher, BigInteger serialNum, X500Name issuer, X500Name subject, Date startDate, Date endDate, String crlDistributionPoints) { try { ClientCertFileBytes result = new ClientCertFileBytes();
KeyPair clientKeyPair = generatePrivateKey(algo);
X509Certificate clientCert = signAndGetCustomX509Certificate( false, clientKeyPair.getPublic(), caPrivateKey, caPublicKey, serialNum, issuer, subject, startDate, endDate, crlDistributionPoints );
byte[] p12FileBytes = getP12FileBytes(clientKeyPair, cipher, clientCert, friendlyName); String clientSerialNo = clientCert.getSerialNumber().toString(16);
result.setP12FileBytes(p12FileBytes); result.setClientSerialNo(clientSerialNo); return result; } catch (Exception e) { log.error("CA 签发 client 证书失败,friendlyName:{},subject:{}", friendlyName, subject, e); } return null; }
public static ClientCertFileBytes generateClientFileBytes(CertAlgo algo, PrivateKey caPrivateKey, String friendlyName, String cipher, BigInteger serialNum, X500Name issuer, X500Name subject, Date startDate, Date endDate, String crlDistributionPoints) { try { PublicKey caPublicKey = derivePublicKeyFromPrivateKey(caPrivateKey); return generateClientFileBytes(algo, caPrivateKey, caPublicKey, friendlyName, cipher, serialNum, issuer, subject, startDate, endDate, crlDistributionPoints); } catch (Exception e) { log.error("CA 签发 client 证书失败,friendlyName:{},subject:{}", friendlyName, subject, e); } return null; }
public static ClientCertFileBytes generateClientFileBytes(CertAlgo algo, PrivateKey caPrivateKey, X509Certificate caCert, String friendlyName, String cipher, BigInteger serialNum, X500Name issuer, X500Name subject, Date startDate, Date endDate, String crlDistributionPoints) { return generateClientFileBytes(algo, caPrivateKey, caCert != null ? caCert.getPublicKey() : null, friendlyName, cipher, serialNum, issuer, subject, startDate, endDate, crlDistributionPoints); }
public static void revokedCertificate(File targetCrlFile, PrivateKey caPrivateKey, X500Name issuer, BigInteger revokedSerialNum, Date nextUpdateDate) throws Exception { X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date()); crlBuilder.addCRLEntry(revokedSerialNum, new Date(), CRLReason.privilegeWithdrawn); crlBuilder.setNextUpdate(nextUpdateDate);
String sigAlgo = getSignatureAlgorithm(caPrivateKey); ContentSigner crlContentSigner = new JcaContentSignerBuilder(sigAlgo).setProvider("BC").build(caPrivateKey); X509CRLHolder crlHolder = crlBuilder.build(crlContentSigner);
try (FileOutputStream crlOutputStream = new FileOutputStream(targetCrlFile)) { crlOutputStream.write(crlHolder.getEncoded()); } }
private static byte[] getP12FileBytes(KeyPair keyPair, String cipher, X509Certificate customCertificate, String friendlyName) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC"); char[] password = cipher.toCharArray(); keyStore.load(null, password); keyStore.setKeyEntry(friendlyName, keyPair.getPrivate(), password, new X509Certificate[]{customCertificate}); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { keyStore.store(bos, password); return bos.toByteArray(); } }
private static X509CertificateHolder getCaX509Holder(KeyPair caKeyPair, BigInteger serialNum, X500Name issuer, X500Name subject, Date startDate, Date endDate, String crlDistributionPoints) throws Exception { PrivateKey privateKey = caKeyPair.getPrivate(); PublicKey publicKey = caKeyPair.getPublic();
JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serialNum, startDate, endDate, subject, publicKey); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(publicKey));
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
KeyUsage caKeyUsage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.digitalSignature); certBuilder.addExtension(Extension.keyUsage, true, caKeyUsage);
if (crlDistributionPoints != null && !crlDistributionPoints.isEmpty()) { GeneralName crlName = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(crlDistributionPoints)); DistributionPointName distPointName = new DistributionPointName(new GeneralNames(crlName)); DistributionPoint distPoint = new DistributionPoint(distPointName, null, null); certBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[]{distPoint})); }
ContentSigner contentSigner = new JcaContentSignerBuilder(getSignatureAlgorithm(privateKey)).setProvider("BC").build(privateKey); return certBuilder.build(contentSigner); }
private static X509Certificate signAndGetCustomX509Certificate(boolean isServer, PublicKey targetPublicKey, PrivateKey caPrivateKey, PublicKey caPublicKey, BigInteger serialNum, X500Name issuer, X500Name subject, Date startDate, Date endDate, String crlDistributionPoints) throws Exception {
JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( issuer, serialNum, startDate, endDate, subject, targetPublicKey ); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(targetPublicKey));
if (caPublicKey != null) { certBuilder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPublicKey)); }
if (isServer) { KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyAgreement); certBuilder.addExtension(Extension.keyUsage, true, keyUsage);
ASN1ObjectIdentifier policyIdentifier = new ASN1ObjectIdentifier("1.3.6.1.4.1.40808.1.3.2"); PolicyInformation policyInformation = new PolicyInformation(policyIdentifier); certBuilder.addExtension(Extension.certificatePolicies, false, new CertificatePolicies(new PolicyInformation[]{policyInformation}));
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth})); } else { KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment); certBuilder.addExtension(Extension.keyUsage, true, keyUsage);
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth})); }
if (crlDistributionPoints != null && !crlDistributionPoints.isEmpty()) { GeneralName crlDistributionPoint = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(crlDistributionPoints)); DistributionPointName distPointName = new DistributionPointName(new GeneralNames(crlDistributionPoint)); DistributionPoint distPoint = new DistributionPoint(distPointName, null, null); certBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[]{distPoint})); }
String sigAlgo = getSignatureAlgorithm(caPrivateKey); ContentSigner signer = new JcaContentSignerBuilder(sigAlgo).setProvider("BC").build(caPrivateKey);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBuilder.build(signer)); }
public static PrivateKey loadPrivateKey(byte[] keyFileBytes, String keyCipher) { try { Object pemObject; try (PEMParser pemParser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(keyFileBytes)))) { pemObject = pemParser.readObject(); }
if (pemObject instanceof PKCS8EncryptedPrivateKeyInfo encryptedKeyInfo) { InputDecryptorProvider decryptProvider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(keyCipher.toCharArray()); PrivateKeyInfo privateKeyInfo = encryptedKeyInfo.decryptPrivateKeyInfo(decryptProvider);
String keyFactoryAlgorithm = getKeyFactoryAlgorithm(privateKeyInfo); KeyFactory keyFactory = KeyFactory.getInstance(keyFactoryAlgorithm, "BC"); return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded())); } } catch (Exception e) { log.error("加载密钥体反序列化失败", e); } return null; }
public static X509Certificate loadCertificate(String certificateFilePath) throws Exception { try (FileInputStream caCertInputStream = new FileInputStream(certificateFilePath)) { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); return (X509Certificate) certificateFactory.generateCertificate(caCertInputStream); } }
public static PKCS10CertificationRequest loadCsr(String csrFilePath) throws IOException { try (FileInputStream in = new FileInputStream(csrFilePath); PEMParser pemParser = new PEMParser(new InputStreamReader(in))) { return (PKCS10CertificationRequest) pemParser.readObject(); } }
private static PublicKey derivePublicKeyFromPrivateKey(PrivateKey privateKey) throws Exception { if (privateKey == null) { return null; } KeyFactory keyFactory = KeyFactory.getInstance(privateKey.getAlgorithm(), "BC");
if (privateKey instanceof ECPrivateKey ecKey) { if (ecKey.getParams() != null) { java.security.spec.ECParameterSpec params = ecKey.getParams(); org.bouncycastle.math.ec.ECCurve curve = org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util.convertCurve(params.getCurve()); org.bouncycastle.math.ec.ECPoint g = org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util.convertPoint(curve, params.getGenerator());
org.bouncycastle.math.ec.ECPoint q = g.multiply(ecKey.getS()).normalize();
return keyFactory.generatePublic(new ECPublicKeySpec( new java.security.spec.ECPoint(q.getAffineXCoord().toBigInteger(), q.getAffineYCoord().toBigInteger()), params )); } } else if (privateKey instanceof RSAPrivateCrtKey rsaKey) { return keyFactory.generatePublic(new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent())); } return null; }
private static String getSignatureAlgorithm(PrivateKey privateKey) { String algo = privateKey.getAlgorithm(); if ("EC".equalsIgnoreCase(algo)) { return "SHA256withECDSA"; } else if ("RSA".equalsIgnoreCase(algo)) { return "SHA256WithRSAEncryption"; } throw new IllegalArgumentException("当前 CA 私钥算法 [" + algo + "] 无法匹配合法签名器类型"); }
private static String getKeyFactoryAlgorithm(PrivateKeyInfo privateKeyInfo) { String algorithm = privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm().getId(); String keyFactoryAlgorithm = "RSA"; if (X509ObjectIdentifiers.id_ea_rsa.getId().equals(algorithm) || "1.2.840.113549.1.1.1".equals(algorithm)) { keyFactoryAlgorithm = "RSA"; } else if (X9ObjectIdentifiers.id_ecPublicKey.getId().equals(algorithm) || "1.2.840.10045.2.1".equals(algorithm)) { keyFactoryAlgorithm = "EC"; } return keyFactoryAlgorithm; } }
|