24.4 Production Tools and Certificate Lifecycle
Certificate lifecycle management includes monitoring, renewal, revocation, and integration with production tools like keytool, openssl, and certificate authorities.
Using keytool Command-Line Tool
// Keytool Integration
public class KeytoolOperations {
public static void printKeytoolCommands() {
System.out.println("=== KEYTOOL COMMAND REFERENCE ===");
System.out.println("\n--- CREATE KEYSTORE ---");
System.out.println("# Generate key pair and self-signed certificate");
System.out.println("keytool -genkeypair -alias mykey \\");
System.out.println(" -keyalg RSA -keysize 2048 \\");
System.out.println(" -validity 365 \\");
System.out.println(" -dname \"CN=localhost, O=MyOrg, C=US\" \\");
System.out.println(" -keystore keystore.p12 \\");
System.out.println(" -storepass changeit -keypass changeit \\");
System.out.println(" -storetype PKCS12");
System.out.println("\n--- LIST ENTRIES ---");
System.out.println("# List all entries");
System.out.println("keytool -list -keystore keystore.p12 -storepass changeit");
System.out.println("\n# List with details");
System.out.println("keytool -list -v -keystore keystore.p12 -storepass changeit");
System.out.println("\n--- GENERATE CSR ---");
System.out.println("keytool -certreq -alias mykey \\");
System.out.println(" -keystore keystore.p12 -storepass changeit \\");
System.out.println(" -file request.csr");
System.out.println("\n--- IMPORT CERTIFICATE ---");
System.out.println("# Import CA certificate");
System.out.println("keytool -import -alias ca \\");
System.out.println(" -file ca.crt \\");
System.out.println(" -keystore truststore.p12 -storepass changeit \\");
System.out.println(" -noprompt");
System.out.println("\n# Import signed certificate");
System.out.println("keytool -import -alias mykey \\");
System.out.println(" -file signed.crt \\");
System.out.println(" -keystore keystore.p12 -storepass changeit");
System.out.println("\n--- EXPORT CERTIFICATE ---");
System.out.println("keytool -export -alias mykey \\");
System.out.println(" -file mycert.crt \\");
System.out.println(" -keystore keystore.p12 -storepass changeit");
System.out.println("\n--- DELETE ENTRY ---");
System.out.println("keytool -delete -alias mykey \\");
System.out.println(" -keystore keystore.p12 -storepass changeit");
System.out.println("\n--- CHANGE PASSWORD ---");
System.out.println("# Change keystore password");
System.out.println("keytool -storepasswd \\");
System.out.println(" -keystore keystore.p12 \\");
System.out.println(" -storepass oldpass -new newpass");
System.out.println("\n# Change key password");
System.out.println("keytool -keypasswd -alias mykey \\");
System.out.println(" -keystore keystore.p12 -storepass changeit \\");
System.out.println(" -keypass oldpass -new newpass");
System.out.println("\n--- CONVERT JKS TO PKCS12 ---");
System.out.println("keytool -importkeystore \\");
System.out.println(" -srckeystore keystore.jks -srcstoretype JKS \\");
System.out.println(" -destkeystore keystore.p12 -deststoretype PKCS12 \\");
System.out.println(" -srcstorepass changeit -deststorepass changeit");
}
// Execute keytool command programmatically
public static String executeKeytool(String... args) throws Exception {
List<String> command = new ArrayList<>();
command.add("keytool");
command.addAll(Arrays.asList(args));
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process = pb.start();
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("keytool failed with exit code " + exitCode);
}
return output.toString();
}
// List keystore entries using keytool
public static void listKeystoreEntries(String keystorePath, String password)
throws Exception {
String output = executeKeytool(
"-list",
"-keystore", keystorePath,
"-storepass", password
);
System.out.println(output);
}
}
Using OpenSSL Commands
// OpenSSL Integration
public class OpenSSLOperations {
public static void printOpenSSLCommands() {
System.out.println("=== OPENSSL COMMAND REFERENCE ===");
System.out.println("\n--- GENERATE PRIVATE KEY ---");
System.out.println("# RSA 2048-bit");
System.out.println("openssl genrsa -out private.key 2048");
System.out.println("\n# RSA 4096-bit with encryption");
System.out.println("openssl genrsa -aes256 -out private.key 4096");
System.out.println("\n# EC P-256");
System.out.println("openssl ecparam -name prime256v1 -genkey -out ec-private.key");
System.out.println("\n--- GENERATE CSR ---");
System.out.println("openssl req -new -key private.key \\");
System.out.println(" -out request.csr \\");
System.out.println(" -subj \"/CN=example.com/O=My Company/C=US\"");
System.out.println("\n--- GENERATE SELF-SIGNED CERTIFICATE ---");
System.out.println("openssl req -x509 -new -nodes \\");
System.out.println(" -key private.key -sha256 -days 365 \\");
System.out.println(" -out certificate.crt \\");
System.out.println(" -subj \"/CN=example.com/O=My Company/C=US\"");
System.out.println("\n--- VIEW CERTIFICATE ---");
System.out.println("openssl x509 -in certificate.crt -text -noout");
System.out.println("\n--- VIEW CSR ---");
System.out.println("openssl req -in request.csr -text -noout");
System.out.println("\n--- VERIFY CERTIFICATE ---");
System.out.println("# Verify against CA");
System.out.println("openssl verify -CAfile ca.crt certificate.crt");
System.out.println("\n# Verify certificate chain");
System.out.println("openssl verify -CAfile root.crt -untrusted intermediate.crt \\");
System.out.println(" certificate.crt");
System.out.println("\n--- CONVERT FORMATS ---");
System.out.println("# PEM to DER");
System.out.println("openssl x509 -in cert.pem -outform DER -out cert.der");
System.out.println("\n# DER to PEM");
System.out.println("openssl x509 -in cert.der -inform DER -out cert.pem");
System.out.println("\n# Create PKCS12 from PEM");
System.out.println("openssl pkcs12 -export \\");
System.out.println(" -in certificate.crt -inkey private.key \\");
System.out.println(" -out keystore.p12 -name myalias \\");
System.out.println(" -passout pass:changeit");
System.out.println("\n# Extract from PKCS12");
System.out.println("openssl pkcs12 -in keystore.p12 -nodes \\");
System.out.println(" -out extracted.pem -passin pass:changeit");
System.out.println("\n--- TEST TLS CONNECTION ---");
System.out.println("# Test HTTPS server");
System.out.println("openssl s_client -connect example.com:443");
System.out.println("\n# Show certificate chain");
System.out.println("openssl s_client -showcerts -connect example.com:443");
System.out.println("\n# Test with specific TLS version");
System.out.println("openssl s_client -tls1_3 -connect example.com:443");
System.out.println("\n--- CHECK CERTIFICATE EXPIRATION ---");
System.out.println("openssl x509 -in certificate.crt -noout -enddate");
System.out.println("\n# Check multiple certificates");
System.out.println("for cert in *.crt; do");
System.out.println(" echo \"$cert:\"");
System.out.println(" openssl x509 -in \"$cert\" -noout -subject -enddate");
System.out.println("done");
}
// Execute openssl command
public static String executeOpenSSL(String... args) throws Exception {
List<String> command = new ArrayList<>();
command.add("openssl");
command.addAll(Arrays.asList(args));
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process = pb.start();
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("openssl failed with exit code " + exitCode);
}
return output.toString();
}
// Verify certificate with openssl
public static boolean verifyCertificate(String certPath, String caPath)
throws Exception {
try {
String output = executeOpenSSL(
"verify",
"-CAfile", caPath,
certPath
);
return output.contains("OK");
} catch (Exception e) {
return false;
}
}
}
Certificate Expiration Monitoring
// Certificate Expiration Monitoring
public class CertificateMonitoring {
// Monitor certificate expiration
public static class ExpirationMonitor {
private final int warningDays;
public ExpirationMonitor(int warningDays) {
this.warningDays = warningDays;
}
public List<ExpirationAlert> checkKeyStore(KeyStore keyStore)
throws Exception {
List<ExpirationAlert> alerts = new ArrayList<>();
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof java.security.cert.X509Certificate) {
java.security.cert.X509Certificate x509 =
(java.security.cert.X509Certificate) cert;
ExpirationAlert alert = checkExpiration(alias, x509);
if (alert != null) {
alerts.add(alert);
}
}
}
return alerts;
}
private ExpirationAlert checkExpiration(String alias,
java.security.cert.X509Certificate cert) {
Date notAfter = cert.getNotAfter();
Date now = new Date();
long diffMs = notAfter.getTime() - now.getTime();
long daysUntilExpiry = java.util.concurrent.TimeUnit.MILLISECONDS
.toDays(diffMs);
if (daysUntilExpiry < 0) {
return new ExpirationAlert(
alias, cert, AlertLevel.CRITICAL,
"Certificate has EXPIRED " + Math.abs(daysUntilExpiry) +
" days ago");
} else if (daysUntilExpiry == 0) {
return new ExpirationAlert(
alias, cert, AlertLevel.CRITICAL,
"Certificate expires TODAY");
} else if (daysUntilExpiry <= 7) {
return new ExpirationAlert(
alias, cert, AlertLevel.ERROR,
"Certificate expires in " + daysUntilExpiry + " days");
} else if (daysUntilExpiry <= warningDays) {
return new ExpirationAlert(
alias, cert, AlertLevel.WARNING,
"Certificate expires in " + daysUntilExpiry + " days");
}
return null;
}
}
static class ExpirationAlert {
final String alias;
final java.security.cert.X509Certificate certificate;
final AlertLevel level;
final String message;
ExpirationAlert(String alias,
java.security.cert.X509Certificate certificate,
AlertLevel level, String message) {
this.alias = alias;
this.certificate = certificate;
this.level = level;
this.message = message;
}
@Override
public String toString() {
return String.format("[%s] %s - %s (expires: %s)",
level, alias, message, certificate.getNotAfter());
}
}
enum AlertLevel {
WARNING, ERROR, CRITICAL
}
// Scheduled monitoring
public static class ScheduledMonitor {
private final ScheduledExecutorService scheduler;
private final ExpirationMonitor monitor;
private final KeyStore keyStore;
public ScheduledMonitor(KeyStore keyStore, int warningDays) {
this.keyStore = keyStore;
this.monitor = new ExpirationMonitor(warningDays);
this.scheduler = Executors.newScheduledThreadPool(1);
}
public void startMonitoring(long intervalHours) {
scheduler.scheduleAtFixedRate(() -> {
try {
List<ExpirationAlert> alerts = monitor.checkKeyStore(keyStore);
if (!alerts.isEmpty()) {
System.out.println("=== CERTIFICATE EXPIRATION ALERTS ===");
for (ExpirationAlert alert : alerts) {
System.out.println(alert);
// In production, send email/notification
if (alert.level == AlertLevel.CRITICAL) {
sendCriticalAlert(alert);
}
}
}
} catch (Exception e) {
System.err.println("Monitoring error: " + e.getMessage());
}
}, 0, intervalHours, java.util.concurrent.TimeUnit.HOURS);
}
private void sendCriticalAlert(ExpirationAlert alert) {
// Send email, Slack message, PagerDuty, etc.
System.err.println("CRITICAL ALERT: " + alert.message);
}
public void stop() {
scheduler.shutdown();
}
}
// Example: Monitor certificates
public static void demonstrateMonitoring(String keystorePath, String password)
throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream is = new FileInputStream(keystorePath)) {
keyStore.load(is, password.toCharArray());
}
ExpirationMonitor monitor = new ExpirationMonitor(30); // 30 days warning
List<ExpirationAlert> alerts = monitor.checkKeyStore(keyStore);
if (alerts.isEmpty()) {
System.out.println("✓ All certificates are valid and not expiring soon");
} else {
System.out.println("⚠ Found " + alerts.size() + " certificate(s) " +
"expiring soon:");
for (ExpirationAlert alert : alerts) {
System.out.println(alert);
}
}
}
}
Automated Certificate Renewal (Let's Encrypt / ACME)
// Automated Certificate Renewal
public class AutomatedRenewal {
public static void printACMEWorkflow() {
System.out.println("=== ACME PROTOCOL (LET'S ENCRYPT) ===");
System.out.println("\n--- USING CERTBOT ---");
System.out.println("# Install certbot");
System.out.println("apt-get install certbot # Debian/Ubuntu");
System.out.println("yum install certbot # RHEL/CentOS");
System.out.println("\n# Obtain certificate (standalone)");
System.out.println("certbot certonly --standalone \\");
System.out.println(" -d example.com -d www.example.com \\");
System.out.println(" --email admin@example.com \\");
System.out.println(" --agree-tos --non-interactive");
System.out.println("\n# Obtain certificate (webroot)");
System.out.println("certbot certonly --webroot \\");
System.out.println(" -w /var/www/html \\");
System.out.println(" -d example.com -d www.example.com");
System.out.println("\n# Automatic renewal (cron)");
System.out.println("0 0,12 * * * certbot renew --quiet \\");
System.out.println(" --post-hook \"systemctl reload nginx\"");
System.out.println("\n--- CONVERT TO JAVA KEYSTORE ---");
System.out.println("# Certificates are stored in:");
System.out.println("# /etc/letsencrypt/live/example.com/");
System.out.println("# - privkey.pem (private key)");
System.out.println("# - cert.pem (certificate)");
System.out.println("# - chain.pem (intermediate chain)");
System.out.println("# - fullchain.pem (cert + chain)");
System.out.println("\n# Create PKCS12 keystore");
System.out.println("openssl pkcs12 -export \\");
System.out.println(" -in /etc/letsencrypt/live/example.com/fullchain.pem \\");
System.out.println(" -inkey /etc/letsencrypt/live/example.com/privkey.pem \\");
System.out.println(" -out keystore.p12 -name tomcat \\");
System.out.println(" -passout pass:changeit");
System.out.println("\n--- ACME4J LIBRARY (JAVA) ---");
System.out.println("// Add dependency: org.shredzone.acme4j:acme4j-client");
System.out.println("// https://github.com/shred/acme4j");
}
// Renewal workflow
public static class RenewalManager {
private final String keystorePath;
private final String keystorePassword;
private final int renewDaysBefore;
public RenewalManager(String keystorePath, String keystorePassword,
int renewDaysBefore) {
this.keystorePath = keystorePath;
this.keystorePassword = keystorePassword;
this.renewDaysBefore = renewDaysBefore;
}
public void checkAndRenew() throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream is = new FileInputStream(keystorePath)) {
keyStore.load(is, keystorePassword.toCharArray());
}
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof java.security.cert.X509Certificate) {
java.security.cert.X509Certificate x509 =
(java.security.cert.X509Certificate) cert;
if (needsRenewal(x509)) {
System.out.println("Certificate needs renewal: " + alias);
renewCertificate(alias, x509);
}
}
}
}
private boolean needsRenewal(java.security.cert.X509Certificate cert) {
Date notAfter = cert.getNotAfter();
Date now = new Date();
long daysUntilExpiry = java.util.concurrent.TimeUnit.MILLISECONDS
.toDays(notAfter.getTime() - now.getTime());
return daysUntilExpiry <= renewDaysBefore;
}
private void renewCertificate(String alias,
java.security.cert.X509Certificate cert) {
System.out.println("Renewing certificate: " + alias);
System.out.println(" Subject: " + cert.getSubjectDN());
System.out.println(" Expires: " + cert.getNotAfter());
// In production:
// 1. Generate new CSR
// 2. Submit to ACME CA (Let's Encrypt)
// 3. Complete challenge (HTTP-01, DNS-01, TLS-ALPN-01)
// 4. Receive signed certificate
// 5. Update KeyStore
// 6. Reload application/server
}
}
}
Hardware Security Module (HSM) Integration
// HSM Integration
public class HSMIntegration {
// Load PKCS11 KeyStore (HSM)
public static KeyStore loadPKCS11KeyStore(String configPath, String pin)
throws Exception {
// Create PKCS11 configuration
String pkcs11Config =
"name = MyHSM\n" +
"library = /path/to/hsm/library.so\n" +
"slot = 0\n";
// Write config to temporary file
Path configFile = Files.createTempFile("pkcs11", ".cfg");
Files.writeString(configFile, pkcs11Config);
// Load PKCS11 provider
Provider pkcs11Provider = Security.getProvider("SunPKCS11");
pkcs11Provider = pkcs11Provider.configure(configFile.toString());
Security.addProvider(pkcs11Provider);
// Load KeyStore
KeyStore keyStore = KeyStore.getInstance("PKCS11", pkcs11Provider);
keyStore.load(null, pin.toCharArray());
return keyStore;
}
// Example: Use HSM for signing
public static byte[] signWithHSM(byte[] data, String alias, String pin)
throws Exception {
KeyStore keyStore = loadPKCS11KeyStore("/path/to/config", pin);
PrivateKey privateKey = (PrivateKey) keyStore.getKey(
alias, pin.toCharArray());
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(data);
return signature.sign();
}
public static void printHSMBestPractices() {
System.out.println("=== HSM BEST PRACTICES ===");
System.out.println("\n1. KEY STORAGE");
System.out.println(" - Store CA private keys in HSM");
System.out.println(" - Never export private keys");
System.out.println(" - Use HSM for production signing");
System.out.println("\n2. ACCESS CONTROL");
System.out.println(" - Strong PIN/password protection");
System.out.println(" - Multi-party authentication for sensitive operations");
System.out.println(" - Audit all HSM access");
System.out.println("\n3. BACKUP AND RECOVERY");
System.out.println(" - HSM key backup procedures");
System.out.println(" - Disaster recovery plan");
System.out.println(" - Key ceremony documentation");
System.out.println("\n4. SUPPORTED HSMs");
System.out.println(" - AWS CloudHSM");
System.out.println(" - Azure Key Vault");
System.out.println(" - Google Cloud KMS");
System.out.println(" - Thales Luna HSM");
System.out.println(" - SafeNet HSM");
}
}
Cloud Key Management Integration
// Cloud Key Management
public class CloudKMS {
public static void printCloudKMSOptions() {
System.out.println("=== CLOUD KEY MANAGEMENT ===");
System.out.println("\n--- AWS KMS ---");
System.out.println("// Add dependency: software.amazon.awssdk:kms");
System.out.println("KmsClient kmsClient = KmsClient.builder()");
System.out.println(" .region(Region.US_EAST_1)");
System.out.println(" .build();");
System.out.println();
System.out.println("// Encrypt data");
System.out.println("EncryptRequest encryptRequest = EncryptRequest.builder()");
System.out.println(" .keyId(\"alias/my-key\")");
System.out.println(" .plaintext(SdkBytes.fromByteArray(data))");
System.out.println(" .build();");
System.out.println("\n--- AZURE KEY VAULT ---");
System.out.println("// Add dependency: com.azure:azure-security-keyvault-keys");
System.out.println("KeyClient keyClient = new KeyClientBuilder()");
System.out.println(" .vaultUrl(\"https://myvault.vault.azure.net\")");
System.out.println(" .credential(new DefaultAzureCredentialBuilder().build())");
System.out.println(" .buildClient();");
System.out.println();
System.out.println("// Get certificate");
System.out.println("KeyVaultCertificate certificate = ");
System.out.println(" keyClient.getCertificate(\"mycert\");");
System.out.println("\n--- GOOGLE CLOUD KMS ---");
System.out.println("// Add dependency: com.google.cloud:google-cloud-kms");
System.out.println("KeyManagementServiceClient client = ");
System.out.println(" KeyManagementServiceClient.create();");
System.out.println();
System.out.println("CryptoKeyName keyName = CryptoKeyName.of(");
System.out.println(" \"project\", \"location\", \"keyring\", \"key\");");
System.out.println("\n--- BENEFITS ---");
System.out.println("✓ Managed infrastructure");
System.out.println("✓ Automatic key rotation");
System.out.println("✓ Compliance certifications (FIPS, PCI-DSS)");
System.out.println("✓ Audit logging");
System.out.println("✓ Fine-grained access control");
}
}
Production Deployment Checklist
// Production Checklist
public class ProductionChecklist {
public static void printChecklist() {
System.out.println("=== PRODUCTION CERTIFICATE CHECKLIST ===");
System.out.println("\n[BEFORE DEPLOYMENT]");
System.out.println("☐ Use trusted CA (not self-signed)");
System.out.println("☐ Certificate validity: 1 year recommended");
System.out.println("☐ Include all Subject Alternative Names");
System.out.println("☐ Use SHA-256 or SHA-384 signature algorithm");
System.out.println("☐ RSA 2048+ or EC P-256+ key size");
System.out.println("☐ Complete certificate chain included");
System.out.println("☐ Private key securely stored");
System.out.println("☐ Test certificate validation");
System.out.println("\n[KEYSTORE CONFIGURATION]");
System.out.println("☐ Use PKCS12 format");
System.out.println("☐ Strong passwords (16+ characters)");
System.out.println("☐ File permissions: 600 (Unix)");
System.out.println("☐ Not in version control");
System.out.println("☐ Separate keystores by purpose");
System.out.println("☐ Backup encrypted keystores");
System.out.println("\n[MONITORING]");
System.out.println("☐ Certificate expiration alerts (30+ days)");
System.out.println("☐ Automated renewal configured");
System.out.println("☐ Certificate validation monitoring");
System.out.println("☐ TLS connection monitoring");
System.out.println("☐ Revocation checking enabled");
System.out.println("\n[RENEWAL PROCESS]");
System.out.println("☐ Documented renewal procedures");
System.out.println("☐ Automated renewal (ACME/Let's Encrypt)");
System.out.println("☐ Testing environment for renewal");
System.out.println("☐ Zero-downtime renewal strategy");
System.out.println("☐ Rollback plan");
System.out.println("\n[SECURITY]");
System.out.println("☐ TLS 1.2+ only (disable TLS 1.0/1.1)");
System.out.println("☐ Strong cipher suites configured");
System.out.println("☐ OCSP stapling enabled");
System.out.println("☐ Certificate pinning (mobile apps)");
System.out.println("☐ CAA DNS records configured");
System.out.println("☐ Regular security audits");
System.out.println("\n[INCIDENT RESPONSE]");
System.out.println("☐ Certificate revocation procedures");
System.out.println("☐ Emergency renewal contacts");
System.out.println("☐ Communication plan for users");
System.out.println("☐ Incident response team defined");
}
}
Best Practices
- Monitoring: Alert 30+ days before certificate expiration.
- Automation: Use ACME protocol for automatic renewal.
- Tools: Master keytool and openssl for certificate operations.
- HSM: Use hardware security modules for CA and production keys.
- Cloud KMS: Consider managed key services for scalability.
- Testing: Test certificate renewal in staging environment.
- Documentation: Document all certificate procedures.
- Access control: Limit access to keystores and private keys.
- Audit logging: Log all certificate operations.
- Incident response: Have procedures for certificate compromise.
- Regular reviews: Audit certificates and keystores quarterly.
- Certificate lifecycle: Plan full lifecycle from generation to revocation.