|
20 | 20 | import java.math.BigInteger; |
21 | 21 | import java.nio.file.Files; |
22 | 22 | import java.nio.file.Path; |
23 | | -import java.security.*; |
| 23 | +import java.security.KeyPair; |
| 24 | +import java.security.KeyPairGenerator; |
| 25 | +import java.security.KeyStore; |
| 26 | +import java.security.KeyStoreException; |
| 27 | +import java.security.PrivateKey; |
| 28 | +import java.security.Security; |
24 | 29 | import java.security.cert.Certificate; |
| 30 | +import java.security.cert.X509CRL; |
25 | 31 | import java.security.cert.X509Certificate; |
26 | 32 | import java.time.Instant; |
27 | 33 | import java.time.temporal.ChronoUnit; |
28 | 34 | import java.util.Collections; |
29 | 35 | import java.util.Date; |
| 36 | +import java.util.concurrent.atomic.AtomicLong; |
| 37 | +import javax.security.auth.x500.X500Principal; |
30 | 38 | import org.bouncycastle.asn1.x500.X500Name; |
31 | 39 | import org.bouncycastle.asn1.x509.AlgorithmIdentifier; |
| 40 | +import org.bouncycastle.asn1.x509.BasicConstraints; |
| 41 | +import org.bouncycastle.asn1.x509.CRLReason; |
| 42 | +import org.bouncycastle.asn1.x509.Extension; |
| 43 | +import org.bouncycastle.asn1.x509.ExtensionsGenerator; |
| 44 | +import org.bouncycastle.asn1.x509.KeyUsage; |
32 | 45 | import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; |
33 | 46 | import org.bouncycastle.cert.X509CertificateHolder; |
| 47 | +import org.bouncycastle.cert.X509v2CRLBuilder; |
34 | 48 | import org.bouncycastle.cert.X509v3CertificateBuilder; |
| 49 | +import org.bouncycastle.cert.jcajce.JcaX509CRLConverter; |
35 | 50 | import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; |
| 51 | +import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; |
| 52 | +import org.bouncycastle.cert.jcajce.JcaX509v2CRLBuilder; |
| 53 | +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; |
36 | 54 | import org.bouncycastle.crypto.util.PrivateKeyFactory; |
37 | 55 | import org.bouncycastle.jce.provider.BouncyCastleProvider; |
38 | 56 | import org.bouncycastle.openssl.jcajce.JcaPEMWriter; |
39 | 57 | import org.bouncycastle.operator.ContentSigner; |
40 | 58 | import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; |
41 | 59 | import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; |
42 | 60 | import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; |
| 61 | +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; |
43 | 62 |
|
44 | 63 | /** |
45 | 64 | * @author Benoit BORDIGONI (benoit.bordigoni at graviteesource.com) |
|
49 | 68 | @SuppressWarnings("java:S112") // only used in tests |
50 | 69 | public class TLSUtils { |
51 | 70 |
|
| 71 | + private static final AtomicLong SERIAL_COUNTER = new AtomicLong(System.nanoTime()); |
| 72 | + |
52 | 73 | static { |
53 | 74 | Security.addProvider(new BouncyCastleProvider()); |
54 | 75 | } |
@@ -168,7 +189,7 @@ public static KeyStore createKeyStore(String alias, Object data, char[] password |
168 | 189 | } |
169 | 190 |
|
170 | 191 | /** |
171 | | - * Happen data to an existing keystore. |
| 192 | + * Append data to an existing keystore. |
172 | 193 | * @param keystore the keystore to happen |
173 | 194 | * @param alias the alias used to add <code>data</code> to the keystore |
174 | 195 | * @param data a {@link X509Pair} or {@link X509Cert} instance |
@@ -212,4 +233,135 @@ private static void addEntry(KeyStore ks, String alias, Object data, char[] pass |
212 | 233 | throw new IllegalArgumentException("%s cannot be added to a key store".formatted(data)); |
213 | 234 | } |
214 | 235 | } |
| 236 | + |
| 237 | + /** |
| 238 | + * Create a Certificate Authority certificate with proper CA extensions. |
| 239 | + * @param commonName the CA common name |
| 240 | + * @return a key pair with a CA certificate |
| 241 | + * @throws Exception when something wrong happened when generating the CA certificate |
| 242 | + */ |
| 243 | + public static X509Pair createCA(String commonName) throws Exception { |
| 244 | + final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); |
| 245 | + keyPairGenerator.initialize(2048); |
| 246 | + final KeyPair caKeyPair = keyPairGenerator.genKeyPair(); |
| 247 | + |
| 248 | + X500Principal subject = new X500Principal("C=FR, O=Gravitee, OU=IntegrationTests, CN=%s".formatted(commonName)); |
| 249 | + |
| 250 | + X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( |
| 251 | + subject, |
| 252 | + calculateSerialNumber(), |
| 253 | + Date.from(Instant.now().minus(1, ChronoUnit.DAYS)), |
| 254 | + Date.from(Instant.now().plus(365, ChronoUnit.DAYS)), |
| 255 | + subject, |
| 256 | + caKeyPair.getPublic() |
| 257 | + ); |
| 258 | + |
| 259 | + certBuilder |
| 260 | + .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) |
| 261 | + .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); |
| 262 | + |
| 263 | + ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caKeyPair.getPrivate()); |
| 264 | + |
| 265 | + JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC"); |
| 266 | + |
| 267 | + X509Certificate certificate = converter.getCertificate(certBuilder.build(signer)); |
| 268 | + |
| 269 | + return new X509Pair(new X509Cert(certificate), new X509Key(caKeyPair.getPrivate())); |
| 270 | + } |
| 271 | + |
| 272 | + /** |
| 273 | + * Create an End Entity certificate signed by a CA. |
| 274 | + * @param caKeyPair the CA key pair to sign the certificate |
| 275 | + * @param clientCN the client common name |
| 276 | + * @return a key pair with an end entity certificate signed by the CA |
| 277 | + * @throws Exception when something wrong happened when generating the certificate |
| 278 | + */ |
| 279 | + public static X509Pair createCASignedCertificate(X509Pair caKeyPair, String clientCN) throws Exception { |
| 280 | + final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); |
| 281 | + keyPairGenerator.initialize(2048); |
| 282 | + final KeyPair clientKeyPair = keyPairGenerator.genKeyPair(); |
| 283 | + |
| 284 | + X500Principal subject = new X500Principal("C=FR, O=Gravitee, OU=IntegrationTests, CN=%s".formatted(clientCN)); |
| 285 | + |
| 286 | + X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( |
| 287 | + caKeyPair.certificate().data().getSubjectX500Principal(), |
| 288 | + calculateSerialNumber(), |
| 289 | + Date.from(Instant.now().minus(1, ChronoUnit.DAYS)), |
| 290 | + Date.from(Instant.now().plus(365, ChronoUnit.DAYS)), |
| 291 | + subject, |
| 292 | + clientKeyPair.getPublic() |
| 293 | + ); |
| 294 | + |
| 295 | + certBuilder |
| 296 | + .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) |
| 297 | + .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); |
| 298 | + |
| 299 | + ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption") |
| 300 | + .setProvider("BC") |
| 301 | + .build(caKeyPair.privateKey().data()); |
| 302 | + |
| 303 | + JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC"); |
| 304 | + |
| 305 | + X509Certificate certificate = converter.getCertificate(certBuilder.build(signer)); |
| 306 | + |
| 307 | + return new X509Pair(new X509Cert(certificate), new X509Key(clientKeyPair.getPrivate())); |
| 308 | + } |
| 309 | + |
| 310 | + /** |
| 311 | + * Generate a Certificate Revocation List (CRL) with optional revoked certificates. |
| 312 | + * @param caKeyPair the CA key pair used to sign the CRL |
| 313 | + * @param revokedCerts optional array of certificates to mark as revoked |
| 314 | + * @return an X509CRL object |
| 315 | + * @throws Exception when something wrong happened when generating the CRL |
| 316 | + */ |
| 317 | + public static X509CRL generateCRL(X509Pair caKeyPair, X509Certificate... revokedCerts) throws Exception { |
| 318 | + X509v2CRLBuilder crlBuilder = new JcaX509v2CRLBuilder( |
| 319 | + caKeyPair.certificate().data().getSubjectX500Principal(), |
| 320 | + Date.from(Instant.now().minus(1, ChronoUnit.DAYS)) |
| 321 | + ); |
| 322 | + |
| 323 | + crlBuilder.setNextUpdate(Date.from(Instant.now().plus(7, ChronoUnit.DAYS))); |
| 324 | + |
| 325 | + JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); |
| 326 | + crlBuilder.addExtension( |
| 327 | + Extension.authorityKeyIdentifier, |
| 328 | + false, |
| 329 | + extUtils.createAuthorityKeyIdentifier(caKeyPair.certificate().data()) |
| 330 | + ); |
| 331 | + |
| 332 | + if (revokedCerts.length > 0) { |
| 333 | + ExtensionsGenerator extGen = new ExtensionsGenerator(); |
| 334 | + extGen.addExtension(Extension.reasonCode, false, CRLReason.lookup(CRLReason.privilegeWithdrawn)); |
| 335 | + var extensions = extGen.generate(); |
| 336 | + for (X509Certificate cert : revokedCerts) { |
| 337 | + crlBuilder.addCRLEntry(cert.getSerialNumber(), new Date(), extensions); |
| 338 | + } |
| 339 | + } |
| 340 | + |
| 341 | + ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption") |
| 342 | + .setProvider("BC") |
| 343 | + .build(caKeyPair.privateKey().data()); |
| 344 | + |
| 345 | + JcaX509CRLConverter converter = new JcaX509CRLConverter().setProvider("BC"); |
| 346 | + |
| 347 | + return converter.getCRL(crlBuilder.build(signer)); |
| 348 | + } |
| 349 | + |
| 350 | + /** |
| 351 | + * Write a CRL to a PEM file. |
| 352 | + * @param crl the CRL to write |
| 353 | + * @param path the file path |
| 354 | + * @throws Exception when something wrong happened when writing the CRL |
| 355 | + */ |
| 356 | + public static void writeCrlToPemFile(X509CRL crl, Path path) throws Exception { |
| 357 | + try (var writer = new StringWriter(); var pemWriter = new JcaPEMWriter(writer)) { |
| 358 | + pemWriter.writeObject(crl); |
| 359 | + pemWriter.flush(); |
| 360 | + Files.writeString(path, writer.toString()); |
| 361 | + } |
| 362 | + } |
| 363 | + |
| 364 | + private static BigInteger calculateSerialNumber() { |
| 365 | + return BigInteger.valueOf(SERIAL_COUNTER.incrementAndGet()); |
| 366 | + } |
215 | 367 | } |
0 commit comments