OpenSSL Essentials: Working with SSL Certificate, Private Key and CSR
Using OpenSSL to generate SSL certificates, private keys and certificate signing requests (CSRs) is an essential skill for any system administrator or security professional. This comprehensive, step-by-step guide will teach you how to use the basic OpenSSL commands to:
Step 1 – Generate a Private Key
The first step is to generate a private key, which will be used later to create the CSR and public key for the SSL certificate.
To generate a 2048-bit RSA private key:
$ openssl genrsa -out private.key 2048
This will create a file called ‘private.key’ that contains the private key. Make sure to protect this file and do not share it publicly.
Some key things to know about private keys:
- They are essential for encrypting and decrypting data.
- They should be kept secret and protected from unauthorized access.
- The stronger the key (e.g., 2048 bits vs. 1024 bits), the more secure it is.
Step 2 – Create a CSR (Certificate Signing Request)
Now that we have a private key, we can generate a CSR or certificate signing request. This is sent to the Certificate Authority (CA) to request a public key certificate.
To generate a CSR:
$ openssl req -new -key private.key -out csr.pem
This will prompt you to enter identifying information that will be included in the CSR such as Country Name, Organization Name etc.
Some things to know about CSRs:
- They contain information about your organization and the domain you want to secure.
- They are used by CAs to verify your identity.
- Never share your private key with the CA. Only send the CSR.
Step 3 – Generate a Self-Signed Certificate
Typically, the CSR is sent to a trusted CA like Comodo, Digicert, etc. to sign and generate the SSL certificate.
For testing purposes, we can create a self-signed certificate which is signed by itself rather than a CA.
To generate a self-signed cert:
$ openssl req -new -x509 -key private.key -out self-signed.crt -days 365
This creates a self-signed certificate called ‘self-signed.crt’ valid for 365 days.
Some points on self-signed certificates:
- They are not trusted by browsers by default, so users will see a warning.
- They are suitable for internal testing and development.
- They should not be used in production environments facing external users.
Step 4 – Generate a CSR and Private Key in One Command
In Step 1 and 2 we generated the private key and CSR separately.
OpenSSL can also generate them in one go:
$ openssl req -newkey rsa:2048 -nodes -keyout private.key -out csr.pem
This generates a 2048 bit RSA private key and CSR saving them to the private.key and csr.pem files respectively.
The -nodes parameter tells OpenSSL to store the private key without password protection.
Step 5 – Generate a PKCS#12 Certificate (.pfx .p12)
In some cases, you may need the SSL certificate and private key to be stored together in a PKCS#12 or .pfx file.
This .pfx file can be directly imported into services like IIS on Windows.
To generate a .pfx file:
$ openssl pkcs12 -export -out public_key.pfx -inkey private.key -in public.crt
Where:
-export
specifies to export to PKCS#12 format-out
specifies the output .pfx filename-inkey
specifies the private key file-in
specifies the certificate file
When running this, OpenSSL will prompt you to set a password for protecting the .pfx file.
Step 6 – Verify a Certificate Signing Request (CSR)
Once you have generated a CSR, it’s good practice to verify it before submitting it to the CA.
To verify a CSR:
$ openssl req -text -noout -verify -in csr.pem
This parses the CSR, prints out its details in text format, and verifies:
- That it is correctly formatted.
- That the signature is valid.
- The certificate request attributes.
This helps catch any errors with the CSR generation before sending it off to a CA.
Step 7 – Verify an SSL Certificate
Once you have obtained an SSL certificate from a CA, you should always verify it before installing on a server.
To verify a certificate:
$ openssl x509 -in public.crt -text -noout
This will print out all the certificate details in text and you can review the following:
- Subject name matches your domain.
- Issuer is a trusted CA.
- Valid dates are correct.
Verifying these details is important to ensure you have a valid certificate from a trusted CA.
Step 8 – Check a Certificate Signing Request (CSR) and Private Key Match
When submitting a CSR to a CA, you send only the CSR itself and keep the private key private.
But how can you verify that the CSR and private key match when you get back the signed certificate?
OpenSSL provides a way to check that:
$ openssl rsa -noout -modulus -in private.key | openssl md5
$ openssl x509 -noout -modulus -in public.crt | openssl md5
This generates an MD5 hash of the modulus of both the private key and certificate. If the hashes match, it proves the CSR and certificate correspond to the same private key.
Always run this check before installing the SSL certificate for better security.
Step 9 – Check an SSL Certificate is Trusted
After installing an SSL certificate, you should validate that it is trusted by major browsers and operating systems.
This can be done using the SSL test from SSL Labs:
https://www.ssllabs.com/ssltest/analyze.html
Submit your domain and it will analyze the SSL certificate, check trust paths and provide a letter grade on how trusted it is.
The certificate should show as trusted on all major browsers like IE, Chrome, Firefox etc.
Step 10 – Revoke an SSL Certificate
If your private key is compromised, or you need to revoke a certificate for any reason, this is done by contacting the issuing CA.
The CA will have a certificate revocation process that will allow you to request revocation of the certificate.
Once revoked, clients will fail to validate the certificate and show warnings if it is still used on a website.
- Reasons for revocation include key compromise, change of affiliation, or certificate misuse.
- Revoked certificates are typically added to a Certificate Revocation List (CRL).
Step 11 – Generate Wildcard SSL Certificate CSR
A wildcard SSL certificate secures unlimited subdomains on a single certificate.
For example, *.example.com will secure www.example.com, mail.example.com etc.
To generate a wildcard CSR:
$ openssl req -newkey rsa:2048 -nodes -keyout private.key -out csr.pem -subj "/CN=*.example.com"
The key portion is specifying CN=*.example.com in the subject to request a wildcard domain.
Some key facts about wildcard certificates:
- They simplify SSL management for multiple subdomains.
- They are generally more expensive than single-domain certificates.
- You still need to properly configure your server to use the wildcard certificate.
Step 12 – Create a Multi-Domain (SAN) Certificate
Multi-domain or SAN certificates secure multiple domains on a single certificate.
For example, a SAN cert can secure example.com and www.example.com together.
To generate a SAN CSR:
$ openssl req -newkey rsa:2048 -nodes -keyout private.key -out csr.pem -subj "/" -reqexts SAN -config <(cat /etc/ssl/openssl.cnf <(printf "[SAN]nsubjectAltName=DNS:example.com,DNS:www.example.com"))
This uses the OpenSSL config file to specify the SAN details.
Some key facts about SAN certificates:
- They are useful for securing multiple related domains with a single certificate.
- They can be more cost-effective than purchasing separate certificates for each domain.
- You need to list all the domains you want to secure in the SAN configuration.
Step 13 – Create Self-Signed Certificates for Internal Systems
Self-signed certificates can be useful for securing internal communications between servers, systems and services within an organization.
For example, securing traffic between a load balancer and web servers; or between internal microservices.
Here is how to generate a self-signed certificate for internal use:
$ openssl req -newkey rsa:2048 -nodes -keyout private.key -x509 -days 365 -out self-signed.crt
And some key points on using self-signed certs internally:
- They avoid the cost of purchasing certificates from a CA for internal use.
- You need to configure your internal systems to trust the self-signed certificate.
- Consider using an internal CA for better manageability if you have many internal systems.
Step 14 – Use OpenSSL to Test SSL Connections
OpenSSL can test SSL connections to check for valid certs, accepted protocol versions, supported ciphers etc.
To test basic SSL connectivity to a server:
$ openssl s_client -connect example.com:443
This will do a TLS handshake with the server and output details like:
- The certificate chain.
- The negotiated cipher suite.
- The SSL protocol version.
s_client is useful for debugging SSL related issues with a server or application.
Step 15 – Use OpenSSL to Benchmark SSL Encryption
OpenSSL includes a benchmarking tool to test encryption speed of algorithms like AES, SHA256 etc.
Basic benchmarking command:
$ openssl speed
This tests default algorithms. To test specific ones:
$ openssl speed -evp aes-128-cbc aes-256-cbc
Sample output:
aes-128-cbc 14768.94k 14678.37k 14672.28k
aes-256-cbc 10528.08k 10506.25k 10475.97k
- The output shows the speed in kilobytes per second.
- This is useful for comparing the performance of different encryption algorithms.
- This can help you choose the best algorithms for your applications.
Conclusion
That covers the core essentials of using OpenSSL for working with SSL certificates and keys. This article provides a comprehensive guide on OpenSSL Essentials.
The key takeaways are:
- Generating private keys, CSRs, and self-signed certificates.
- Verifying CSRs and certificates.
- Checking CSR and private key matches.
- Generating PKCS#12 files.
- Testing SSL connections and benchmarking encryption.
OpenSSL is a powerful toolkit that every security professional should feel comfortable using. Master these basics and you’ll be ready to securely implement SSL in your infrastructure. Understanding OpenSSL Essentials is crucial for securing your systems. This article on OpenSSL Essentials will help you get started.
Alternative Solutions and Elaborations
While OpenSSL is a powerful and versatile tool, alternative solutions exist for managing SSL certificates, private keys, and CSRs. Here are two different approaches, along with explanations and code examples where applicable.
1. Using Let’s Encrypt with Certbot:
Let’s Encrypt is a free, automated, and open Certificate Authority (CA) that provides SSL certificates. Certbot is a free, open-source software tool that automates the process of obtaining and installing Let’s Encrypt certificates.
- Explanation: Let’s Encrypt simplifies the entire process. Certbot handles the key generation, CSR creation, domain verification, and certificate installation. It also automates certificate renewal, which is a critical aspect of maintaining SSL security. This eliminates much of the manual steps involved with OpenSSL and traditional CAs. It’s particularly useful for securing web servers with minimal effort.
- How it Differs from OpenSSL: Instead of manually creating keys and CSRs, you rely on Certbot to interact with Let’s Encrypt. The entire process is automated, making it less prone to human error. The certificates are free and automatically renewed.
-
Code Example (using Certbot on Ubuntu):
First, install Certbot:
sudo apt update sudo apt install certbot python3-certbot-apache
Then, obtain a certificate for your domain (assuming you are using Apache):
sudo certbot --apache -d example.com -d www.example.com
Certbot will guide you through the process. It will automatically configure your Apache web server to use the new certificate. It also sets up automatic renewal.
- Advantages: Free certificates, automated process, automatic renewal.
- Disadvantages: Limited to domain validation (DV) certificates, requires a publicly accessible web server for domain verification, not suitable for internal systems without public DNS records.
2. Using a Certificate Management Platform:
Several commercial and open-source certificate management platforms offer a centralized approach to managing SSL/TLS certificates. Examples include Keyfactor, Venafi, and Sectigo Certificate Manager.
- Explanation: These platforms provide a centralized repository for storing and managing certificates and private keys. They offer features such as certificate discovery, automated renewal, policy enforcement, and reporting. They integrate with various CAs and can automate the entire certificate lifecycle.
- How it Differs from OpenSSL: Instead of manually using OpenSSL commands, you interact with the platform’s interface or API. The platform handles the complexities of key generation, CSR creation, certificate enrollment, installation, and renewal. It provides a single pane of glass for managing all your certificates across your infrastructure.
- Advantages: Centralized management, automated lifecycle management, policy enforcement, improved security, reduced administrative overhead.
- Disadvantages: Can be expensive (especially for commercial platforms), requires initial setup and configuration, may have a learning curve.
-
Code Example (Illustrative – API interaction will vary depending on the specific platform):
This is a conceptual example of using a platform’s API (e.g., using Python and the
requests
library) to request a certificate:import requests import json # Platform API endpoint api_url = "https://your-certificate-platform.com/api/v1/certificates" # Authentication token api_token = "YOUR_API_TOKEN" # Certificate request data data = { "domain": "example.com", "type": "dv", # Domain Validated "key_algorithm": "rsa", "key_size": 2048 } headers = { "Authorization": f"Bearer {api_token}", "Content-Type": "application/json" } response = requests.post(api_url, headers=headers, data=json.dumps(data)) if response.status_code == 201: print("Certificate request submitted successfully.") print(f"Certificate ID: {response.json()['id']}") else: print(f"Error submitting request: {response.status_code} - {response.text}")
This code snippet demonstrates how you might interact with a certificate management platform’s API to request a certificate. The specific API endpoints, authentication methods, and data structures will vary depending on the platform you are using.
These alternatives offer different approaches to SSL certificate management, ranging from the simplicity of Let’s Encrypt with Certbot to the comprehensive features of certificate management platforms. The best choice depends on your specific needs, technical expertise, and budget.