How to use the command 'openssl req' (with examples)
The ‘openssl req’ command is a part of the OpenSSL toolkit and is used to manage PKCS#10 Certificate Signing Requests (CSR). A CSR is a message sent from an applicant (individual or organization) to a certificate authority (CA) to request the issuance of a digital certificate. The ‘openssl req’ command allows users to generate CSRs, as well as self-signed certificates.
Use case 1: Generate a certificate signing request to be sent to a certificate authority
Code:
openssl req -new -sha256 -key filename.key -out filename.csr
Motivation: This use case is useful when you need to request a digital certificate from a certificate authority (CA) for a domain or to secure communication between servers.
Explanation:
req
: Command to manage PKCS#10 Certificate Signing Requests.-new
: Generates a new CSR.-sha256
: Specifies the message digest algorithm to be used for the CSR. In this case, SHA-256 is used.-key filename.key
: Specifies the private key file used to generate the CSR. Replace ‘filename.key’ with the path to your private key file.-out filename.csr
: Specifies the output file name for the generated CSR. Replace ‘filename.csr’ with the desired name and path for your CSR file.
Example OUTPUT: A new CSR named ‘filename.csr’ will be generated based on the private key provided. The CSR file can then be sent to a certificate authority for further processing.
Use case 2: Generate a self-signed certificate and a corresponding key-pair, storing both in a file
Code:
openssl req -new -x509 -newkey rsa:4096 -keyout filename.key -out filename.cert -subj "/C=XX/CN=foobar" -days 365
Motivation: This use case is useful when you need to generate a self-signed certificate for testing or development purposes, or when you want to quickly secure a server without involving a certificate authority.
Explanation:
-x509
: Generates a self-signed certificate instead of a CSR.-newkey rsa:4096
: Generates a new RSA key-pair with a key size of 4096 bits.-keyout filename.key
: Specifies the output file name for the generated private key. Replace ‘filename.key’ with the desired name and path for your private key file.-out filename.cert
: Specifies the output file name for the generated self-signed certificate. Replace ‘filename.cert’ with the desired name and path for your certificate file.-subj "/C=XX/CN=foobar"
: Sets the subject field of the certificate to “/C=XX/CN=foobar”. Replace ‘XX’ with the appropriate country code and ‘foobar’ with the desired common name (e.g., domain name).-days 365
: Specifies the validity period in days for the generated certificate.
Example OUTPUT: A self-signed certificate named ‘filename.cert’ and a private key named ‘filename.key’ will be generated. The certificate will be valid for 365 days and can be used for securing communication or testing purposes.